Reputation: 4869
I have a base class called "Entity" which has a static method called "construct" that returns an Entity instance. I have several different subclasses of this class (for demonstration assume we have "Fruit" and "Vegetable" as subclasses). I would like to be able to do something along the following lines:
Entity a = someFunction(Fruit, textfile)
someFunction would then pass textfile to Fruit.construct and return the Entity generated. Is there a simple way to do this?
Upvotes: 12
Views: 16309
Reputation: 15219
You mean something like this:
public <T> T someFunction(Class<T> clazz, String textFile) throws Throwable {
return clazz.newInstance();
}
The above code will use the no-arguments Constructor of the class (assuming there's one).
If your class needs to be instantiated with a specific constructor, you can do follow this example:
public <T> T someFunction(Class<T> clazz, String textFile) throws Throwable {
// Here I am assuming the the clazz Class has a constructor that takes a String as argument.
Constructor<T> constructor = clazz.getConstructor(new Class[]{String.class});
T obj = constructor.newInstance(textFile);
return obj;
}
Upvotes: 7
Reputation: 773
Here is a implementation :
public <T extends Entity> T someMethod(Class<T> entityClass, File file) throws InstantiationException, IllegalAccessException {
T newEntity = entityClass.newInstance();
// do something with file
// ...
return newEntity;
}
You should look to
Upvotes: 1
Reputation: 46
You are trying to implement an object-oriented design pattern, Strategy, using procedural code. Don't do it.
Instead, create an interface called EntityConstructor
, which defines the method construct()
. Make Fruit
and Vegetable
implement that interface. Then change someFunction()
to take an instance of that interface.
Upvotes: 1
Reputation: 70909
Fruit
in your example is a type, and while Fruit.eat()
might refer to a static method, Fruit
is not a "static class".
There is a "class Object" which is actually an Object
that represents the class. Pass it instead. To get to it, they syntax Fruit.class
is used.
Upvotes: 2
Reputation: 2772
Static methods are not inherited, per se, in that if your code has Entity.construct(...) it will not dynamically link that to the sub class.
The best way to accomplish what you are asking for is to use reflection to invoke the construct method on the Fruit class (or whatever class was passed into the someFunction() method.
Upvotes: 0
Reputation: 54074
Use a factory pattern instead.
Pass the text file to the factory method that will use it to return the proper concrete instance of Entity
Upvotes: 10
Reputation: 200168
Pass Fruit.class
to the function and then use reflection on that class object to invoke the proper constructor. Note that this will couple your superclass quite tightly to its subclasses by demanding that constructor to exist.
Upvotes: 3