有一种方法可以避免慢速反射从一个类创建一个实例,显然在另一个方法中?例如:
Foo foo = new Foo();
foo.create(Dog.class, "rocky");
class Foo {
Object create(Class object, String dogName) {
//create an instance of the class 'object' here passing the argument to constructor
//e.g. Object obj = new object(dogName); <-- this is wrong
return obj;
}
}
class Dog extends Animal {
Dog(String dogName) {
this.name = dogName;
}
}
class Animal {
String name;
}
我无法使用关键字&#34; new&#34;创建实例,因为我必须以动态方式在另一个方法中创建实例...
你有全权改善这个代码的最佳方式(如性能):)谢谢!
答案 0 :(得分:3)
让您的狗和动物类保持不变。并使用Builder模式
public interface Builder<T> {
public T build(String nameString);
}
public static void main(String[] args){
Builder<Dog> builder = new Builder<Dog>()
{
@Override
public Dog build(String nameString)
{
return new Dog(nameString);
}
};
Dog dog = builder.build("Rocky");
System.out.print(dog.name);
}
Instantiating object of type parameter的答案也会进一步解释。
答案 1 :(得分:2)
public <T> T create(Class<T> myClass, String constructorArg)
throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
Constructor<T> toCall = myClass.getConstructor(String.class);
return toCall.newInstance(constructorArg);
}