Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass any Class as a parameter for a method

Tags:

java

generics

This has probably been asked before and I've seen a few similar/along the lines, but didn't quite understand it.

In Java, how do make it so a method accepts any class as a parameter?

For example,

public (AnyClass) myMethod(String whatever, (AnyClass) thisClass){

}

to be used like:

myMethod("Hello", ClassA);
myMethod("Hello", ClassB);

Thanks for any help!

Edit:

Usage example was asked for; What I'm doing is mapping a JSON string to a POJO, but trying to abstract this whole thing out so it can be reused. So - I need to be able to pass through any class, and the JSON string (or HttpConn), then build then use Jackson to build that POJO and return the object, of whatever type that may be.

(An idea of what I want to do):

public Class<?> doSomething(String jsonString, Class<?> clazz){
    clazz newInstance = mapper.readValue(jsonString, clazz);
    return clazz;
}

called like:

ClassA test = doSomething("String One", ClassA.class);
ClassB testTwo = doSomething("Different format string", ClassB.class);

Hope that helps understanding of the problem... and my understanding of the solutions!

like image 868
AristotleTheAxolotl Avatar asked Feb 12 '26 06:02

AristotleTheAxolotl


1 Answers

1) Without type information:

public static Class<?> myMethod(String text, Class<?> clazz) {
    // body
    return clazz;
}

Client code:

public static void main(String[] args) {
    Class<?> clss = myMethod("Example", String.class);
}

2) With type information:

public static <T> Class<T> myMethod(String x, Class<T> clazz) {
    // body
    return clazz;
}

Client code:

public static void main(String[] args) {
    Class<String> clsStr = myMethod("Example", String.class);
    Class<?> clsAny = myMethod("Example", String.class);
}

3) Raw type (will work but NOT recommended):

public static Class myMethod(String x, Class clazz) {
    // body
    return clazz;
}

Client code:

public static void main(String[] args) {
    Class<String> clsStr = myMethod("Example", String.class); // warning for Unchecked Assignment 
    Class<?> clsAny = myMethod("Example", String.class);
    Class clsRaw = myMethod("Example", String.class);
}

4) With type information defined at class level:

public class Main<T> { 

    // cannot be static
    public Class<T> myMethod(String x, Class<T> clazz) {
        // body
        return clazz;
    }
}

Client code:

public static void main(String[] args) {
    Main<String> m = new Main<>();
    Class<String> cls = m.myMethod("x", String.class);
}
like image 55
J-Alex Avatar answered Feb 15 '26 19:02

J-Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!