Java Passing in Type as functional parameter

I am coming from a Python background, and in Python you can pass the type of an object as a parameter. But in Java you can't do that, any tips on how to get something like this to work?

private void function(Type TypeGoesHere)
    Stock s = new TypeGoesHere();
    s.analyze();
}

      

+3


source to share


3 answers


Java does not support Pythons method for function and class references. To achieve this behavior, you need to use two cutting edge technologies: generics and reflective. Explaining these concepts is outside the scope of the SO answer. You should read the Java manual to learn about them.

But here's an example of how it would look if we assume that this class has a no-argument constructor:

public <T extends Stock> void analyzeNewStock(Class<T> clazz) throws Exception {
  Stock s = clazz.newInstance();
  s.analyze();
}

      



Then call this function with analyzeNewStock(MyStock.class)

.

Since this is a rather complex and error prone approach, you would rather define an interface that instantiates Stock

:

public interface StockProvider {
  Stock createStock(String value);
}

public class MyStockProvider implements StockProvider {
  private final String valueTwo;

  public MyStockProvider(String valueTwo) {
    this.valueTwo = valueTwo;
  }

  @Override
  public Stock createStock(String valueOne) {
    return new MyStock(valueOne, valueTwo);
  }
}

public class MyOtherClass {
  public void analyzeNewStock(StockProvider provider) {
    provider.createStock("Hi!").analyze();
  }

  public static void main(String[] args) {
    analyzeNewStock(new MyStockProvider("Hey!"));
  }
}

      

+2


source


In Java, you can pass a class. You can do it like this:

private void function(Class c)

      

However, this is not a very common leprosy. You can probably get what you need by looking at the strategy pattern or the correct use of object oriented programming (polymorphism).



If you're looking for a way to create some objects, take a look at the Factory Pattern.

If you want to create a generic class - take a look at this detailed answer: fooobar.com/questions/15718 / ...

+2


source


You can use generics . For example:

private <T> void function(Class<T> clazz) {
    try{
        T t = clazz.newInstance();
        //more code here
    }catch(InstantiationException | IllegalAccessException ex){
        ex.printStackTrace();
    }
}

      

Class<T> clazz

shows the type of instantiation. try/catch

is only intended to prevent stopping errors in your code. This same idea is expanded on this SO page . More details here .

However, I'm not entirely sure why you want to do this. There can be an easy workaround using a simple interface. Since you already know you want an object with a type Stock

, you can pass the implementation of the interface. For example:

//interface to implement
public interface Stock {
    public void analyze();
}

//rewrite of function
private void function(Stock s){
    s.analyze();
}

      

And using two call methods function

:

//first way
public class XYZ implements Stock{
    public void analyze(){
        //some code here
    }
}

//calling the function
function(new XYZ());

//second way
function(new Stock(){
    public void analyze(){
        //your code here
    }
});

      

+1


source







All Articles