Java 方法提取、泛型、反射
第一个代码:Java 方法提取、泛型、反射,java,generics,reflection,refactoring,Java,Generics,Reflection,Refactoring,第一个代码: Bond[] bonds = null; try { JSONArray jsonArray = new JSONArray(result); bonds = new Bond[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray
Bond[] bonds = null;
try
{
JSONArray jsonArray = new JSONArray(result);
bonds = new Bond[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject json = jsonArray.getJSONObject(i);
bonds[i] = new Bond(json);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
可以使用以下语法使用带参数的构造函数(我假设构造函数的参数是
JSONObject
,并且构造函数是公共的-如果不是,请使用getDeclaredConstructor
方法):
Class cls=Announcement.Class//方法的第二个参数
objects[i]=cls.getConstructor(JSONObject.class).newInstance(json);
您可以使用泛型来提供类型安全性并避免铸件,但您必须返回一个列表
static <T> List<T> getObjectsArray(String jsonString, Class<T> cls) {
...
}
静态列表getObjectsArray(字符串jsonString,类cls){
...
}
如果在Announcement和Bound之间有一个公共类型(接口),那么最好像这样绑定泛型类型:
static <T extends YourSuperType> ...
静态。。。
那不应该是“Announcement.class”?cls=Announcement.class
和cls.getDeclaredConstructor(JSONObject.class)
获取Announcement的构造函数,该构造函数将JSONObject作为参数(除非我把事情弄混了)。哦,等等。你说得对!很抱歉最好是显示cls
是Announcement.class
objects[i] = new Announcement(json); // FIXME: How to pass "json" arg to the constructor with cls.newInstance()?
Class<Announcement> cls = Announcement.class; //the second argument of your method
objects[i] = cls.getConstructor(JSONObject.class).newInstance(json);
static <T> List<T> getObjectsArray(String jsonString, Class<T> cls) {
...
}
static <T extends YourSuperType> ...