<分区>
我正在存储一个 .class
... 列表(不管你怎么调用它们)。例如MyClass1.class、MyClass2.class等
在这种情况下,对象是各种/不同的 fragment ,但它们都通过 newInstance() 接受一个长参数。
我希望能够从这样一个列表的第 i 个位置实例化对象。我该怎么做?
<分区>
我正在存储一个 .class
... 列表(不管你怎么调用它们)。例如MyClass1.class、MyClass2.class等
在这种情况下,对象是各种/不同的 fragment ,但它们都通过 newInstance() 接受一个长参数。
我希望能够从这样一个列表的第 i 个位置实例化对象。我该怎么做?
最佳答案
要创建类的实例,可以使用反射。
获取类就像使用所有 List 实现附带的 get 方法一样简单,当然要确保您正在访问的 index 确实存在。获取类对象后,您可以使用反射来实例化它:
示例 #1,无参数构造函数:
Class<?> myClass = String.class;
try {
Object objectOfClass = myClass.newInstance();
} catch (InstantiationException | IllegalAccessException e1) {
e1.printStackTrace();
}
示例 #2 带参数的构造函数:
Class<?> myClass = String.class;//Get the class from the list. For this example i used String.class
try {
Constructor<?> classConstructor = myClass.getConstructor(byte[].class); //Here we get the constructor we aim for. String has a constructor which accepts a byte array as parameter, so all i do is getConstructor with patameter byte[].class.
//if your class accepts two parameters such as long and int, you will have to do .getConstructor(long.class, int.class); in the correct order ofcourse.
Object objectOfClass = classConstructor.newInstance(new byte[]{33,25,111,34});//here we call the constructor and we provide the parameter values it takes to it. So thats why i provide a byte array. In the case of the long and int constructor mentioned above, you will have to invoke it like this: .newInstance(214324324234,34242);
} catch (ReflectiveOperationException e) { //Reflective operation exception wraps up all reflection related exceptions, so we catch it instead of having to manually catch each of them.
e.printStackTrace();
}
编辑 #1 在评论中与 OP 交谈后,必须提供一段更具体的代码:
// NOTE: THIS PIECE OF CODE ASUMES THAT Fragment IS THE SUPERCLASS OF ALL IMPLEMENTATIONS IN THE LIST!
List<Class<? extends Fragment>> l = new ArrayList<>();//This is your list of fragments
Fragment fragmentObject = (Fragment) l.get(3).newInstance();//use default constructor with no arguments. I am randomly getting index 3
Bundle arguments = new Bundle();
arguments.putInt("someValue",123);
fragmentObject.setArguments(arguments);
关于java - 从 .class 或类似的东西实例化 Fragment 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37632559/