Calling a static method using generic type

Viewed 25300

No static member can use a type parameter, but is it possible to call a static member using the generic type parameter? For example:-

abstract class Agent<A>{
    void callAgent();
    Agent(){
        A.add();                    
    }
}

Here add() is a static method.

There are some C# questions and answers on a similar topic but I'm not too sure how to go about it in Java.

6 Answers

It is handy to get a value from an enum you don't know beforehand.

public static <T extends Enum<T>> T enumFromName(String name, Class<T> clazz) {
    return StringUtils.isEmpty(value) ? null : T.valueOf(clazz, name);
}

Having:

enum ProductType { FOOD, ELECTRONICS, ... }

You can do:

ProductType p = enumFromName("FOOD", ProductType.class);

I guess you can also take advantage of this in your own classes, although I would not recommend using static too much.

You can use reflection for calling static method of class T. For example:

public Agent<T>{

    private final Class<T> clazz;

    public Agent(Class<T> clazz){
        this.clazz = clazz;
        executeAddMethodOfGenericClass();
    }

    public void executeAddMethodOfGenericClass() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = clazz.getMethod("add");
        method.invoke(null);
    }
}

But i can get exception. Be careful.

Related