实例化一个类,传入java?

eJm*_*eJm 1 java objective-c instantiation

我有一个关于在一个方法中作为参数传递的类中实例化java中的新对象的查询,例如:

void myMethod(Class aReceived){
    object = new aReceived       // object will be a superclass of aReceived
}
Run Code Online (Sandbox Code Playgroud)

我已经看到使用Objective-C在几行中完成了这一点,但我不确定它在java中是如何工作的.

你能帮我吗?

提前致谢 ;)

Ita*_*man 5

如果要通过no-arg构造函数创建对象:

void myMethod(Class<?> aReceived) {
  Object newObject = aReceived.newInstance();
  ...
}
Run Code Online (Sandbox Code Playgroud)

如果要通过双arg构造函数创建对象(使用String,int):

void myMethod(Class<?> aReceived) {
  Object newObject = aReceived.getConstructor(String.class, int.class)
      .newInstance("aaa", 222);
  ...
}
Run Code Online (Sandbox Code Playgroud)

最后,您可以使用泛型来正确设置newObject变量的类型(在上述任一片段的顶部):

void myMethod(Class<T> aReceived) {
  T newObject = aReceived.getConstructor(String.class, int.class)
      .newInstance("aaa", 222);  
  ...
  // Sadly, due to erasure of generics you cannot do newObject.SomeMethodOfT() 
  // because T is effectively erased to Object. You can only invoke the 
  // methods of Object and/or use refelection to dynamically manipulate newObject
}
Run Code Online (Sandbox Code Playgroud)

[附录]

你怎么称呼这种方法?

选项1 - 当你知道,在代码编写时,你想要传递给方法的类:

myMethod(TestClass.class)
Run Code Online (Sandbox Code Playgroud)

选项2 - 当要实例化的类的名称仅在运行时知道时,作为字符串:

String className = ....; // Name of class to be instantiated
myMethod(Class.forName(className));
Run Code Online (Sandbox Code Playgroud)