我正在使用反射编写一个类,该类将从 JSONArray jArr 的元素创建对象(我作为参数 Base 传递的类型),并将它们添加到 ArrayList objectList 中。一切都很好,直到我到达这一步:
for(int i = 0; i < jArr.length(); i++) {
objectList.add(Base.getConstructor(new Class[]{JSONObject.class}).newInstance(jArr.getJSONObject(i)));
}
在运行时,我收到以下错误:
java.lang.NoSuchMethodException: <init> [class org.json.JSONObject]
从我从谷歌收集的信息来看,当您尝试使用不正确的参数调用构造函数时,似乎会发生此错误,但我不确定为什么这会适用于此。
编辑:这是完整的错误,根据要求:
06-15 18:35:55.245 1919-1919/com.example.ben.phptest W/System.err: java.lang.NoSuchMethodException: [class org.json.JSONObject]
06-15 18:35:55.245 1919-1919 /com.example.ben.phptest W/System.err:在 java.lang.Class.getConstructorOrMethod(Class.java:472)
06-15 18:35:55.255 1919-1919/com.example.ben.phptest W/ System.err:在 java.lang.Class.getConstructor(Class.java:446)
06-15 18:35:55.255 1919-1919/com.example.ben.phptest W/System.err:在 com.example.ben .phptest.PHPList.(PHPList.java:58)
06-15 18:35:55.255 1919-1919/com.example.ben.phptest W/System.err:在 com.example.ben.phptest.MainActivity.onCreate( MainActivity.java:35)
06-15 18:35:55.255 1919-1919/com.example.ben.phptest W/System.err:在 android.app.Activity.performCreate(Activity.java:5231)
06-15 18:35:55.255 1919-1919/com.example.ben.phptest W/System.err:在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-15 18:35:55.255 1919- 1919/com.example.ben.phptest W/System.err:在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-15 18:35:55.255 1919-1919/com.example.ben.phptest W /System.err﹕在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-15 18:35:55.255 1919-1919/com.example.ben.phptest W/System.err﹕在 android.app。 ActivityThread.access$800(ActivityThread.java:135)
06-15 18:35:55.255 1919-1919/com.example.ben.phptest W/System.err:在 android.app.ActivityThread$H.handleMessage(ActivityThread.java :1196)
06-15 18:35:55.265 1919-1919/com.example.ben.phptest W/System.err:在 android.os.Handler.dispatchMessage(Handler.java:102)
06-15 18:35:55.265 1919- 1919/com.example.ben.phptest W/System.err:在 android.os.Looper.loop(Looper.java:136)
06-15 18:35:55.265 1919-1919/com.example.ben.phptest W /System.err:在 android.app.ActivityThread.main(ActivityThread.java:5017)
06-15 18:35:55.265 1919-1919/com.example.ben.phptest W/System.err:在 java.lang。 reflect.Method.invokeNative(Native Method)
06-15 18:35:55.265 1919-1919/com.example.ben.phptest W/System.err: at java.lang.reflect.Method.invoke(Method.java:515 )
06-15 18:35:55.265 1919-1919/com.example.ben.phptest W/System.err﹕在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-15 18:35:55.265 1919-1919/com.example.ben.phptest W/System.err﹕在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-15 18:35 :55.265 1919-1919/com.example.ben.phptest W/System.err:在 dalvik.system.NativeStart.main(Native Method)
(第 58 行是上面循环的核心)
附带说明一下,我传入的类绝对接受 JSONObject 作为其唯一且唯一的构造函数参数:
Person(JSONObject obj) throws JSONException