请参阅下面的代码并告诉我什么是不同的。
public class c1
{
//....
}
Class c2 = obj.getClass();
Object o1 = new c1();
Object o2 = new c2(); // <<----- here
错误的结束线???
如何创建c2 ????
的对象编辑:
int[] s1 = new int[]{4,5,6};
char[] s2 = new char[]{'a'.'b'};
Integer[] new = convertPrimitiveArrayToObject(new Object[]{s1});
Character[] new = convertPrimitiveArrayToObject(new Object[]{s2});
public static <T> T[] convertPrimitiveArrayToObject(Object[] primitive)
{
Object x = primitive[0];
Class type = x.getClass().getComponentType(); // => int OR char
type[] x2 = (type[]) x; // I need to convert array to (int/char/...)
//......
}
答案 0 :(得分:1)
您需要使用反射,首先阅读Java反射
这会对你有所帮助 Creating New Class Instances
创建对象
Object object = null;
try {
Class clazz = Class.forName("yor fully qualified class name");
object = clazz.newInstance();
} catch (InstantiationException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
}
答案 1 :(得分:0)
Object o2 = (C1) c2.newInstance();