質問

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;
}

I cannot create the instance using the keyword "new", because I must create the instance in another method in a dynamic way...

You have carte blanche to improve in the best way (like performance) this code :) Thank you!

役に立ちましたか?

解決

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);

}

The answers over at Instantiating object of type parameter explain it further as well.

他のヒント

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);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top