How to pass a static class as an argument in Java

I have a base class called "Entity" that has a static method called a "construct" that returns an Entity instance. I have several different subclasses of this class (for demonstration, suppose we have “Fruits” and “Vegetables” as subclasses). I would like to do something in the following lines:

Entity a = someFunction(Fruit, textfile) 

someFunction will then pass the text file to Fruit.construct and return the created Entity. Is there an easy way to do this?

+8
java design-patterns
source share
7 answers

Use factory template .
Pass the text file to the factory method, which will use it to return a specific concrete Entity instance

+10
source share

Pass Fruit.class function, and then use the reflection of this class object to invoke the appropriate constructor. Note that this is enough to connect your superclass to its subclasses, requiring the constructor to exist.

+3
source share

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 (if any).

If your class should be created using a specific constructor, you can run the following 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; } 
+3
source share

Fruit in your example is a type, and although Fruit.eat() may refer to a static method, Fruit not a "static class".

There is a “class object”, which is actually an Object that represents a class. Pass it on instead. To get to it, use the syntax Fruit.class .

+1
source share

Static methods themselves are not inherited: if your code has Entity.construct (...), it will not dynamically bind this to a subclass.

The best way to accomplish what you are asking for is to use reflection to invoke the Fruit class construct method (or any other class passed to the someFunction () method.

0
source share

You are trying to implement the object-oriented Strategy design pattern using procedural code. Do not do this.

Instead, create an interface called EntityConstructor that defines the construct() method. Make Fruit and Vegetable implement this interface. Then modify someFunction() to take an instance of this interface.

0
source share

Here is the 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 have to look

0
source share

All Articles