如何以最好的方式从类对象创建一个实例 [英] how to create in best way an instance from the class object
问题描述
有一种方法可以避免慢速反射从一个类创建一个实例,显然在另一个方法中?例如:
There is a way to avoid the slow reflection to create an instance from a class, obviously within another method ? For example:
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;
}
$ b $ p我无法使用关键字new创建实例,在另一种方法中的实例以动态的方式...
I cannot create the instance using the keyword "new", because I must create the instance in another method in a dynamic way...
你有最好的方式(如性能)改进这个代码:)谢谢! p>
You have carte blanche to improve in the best way (like performance) this code :) Thank you!
推荐答案
让你的Dog和Animal类保持一致。并使用Builder模式
Leave your Dog and Animal classes the same. and use the Builder pattern
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);
}
a href =http://stackoverflow.com/questions/299998/instantiating-object-of-type-parameter>类型参数的实例化对象也会进一步解释。
The answers over at Instantiating object of type parameter explain it further as well.
这篇关于如何以最好的方式从类对象创建一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!