Pass any Class as a parameter for a method

AristotleTheAxolotl :

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!

DodgyCodeException :

In your latest edit, your usage example is like this:

ClassA test = doSomething("String One", ClassA.class);

The question shows confusion between a class name, the Class object and an instance of a class. So just to clarify, using the above example:

  • A class name – ClassA – is used to declare a variable.

  • A Class instance – ClassA.class – is a singleton object that holds information about a class and can be passed as an argument to a method.

  • An instance of a class – test – is an object. It's usually created using the new keyword.

You can't use a Class object, such as ClassA.class, directly in a declaration. Instead, you have to call the newInstance() method of the Class class. That method can be used only if your class has a no-args constructor. To create an instance with constructor arguments, use something like this:

public <T> T doSomething(String jsonString, Class<T> clazz) throws ReflectiveOperationException {
    Constructor<T> constructor = clazz.getConstructor(String.class);
    return constructor.newInstance(jsonString);
}

The above method creates an instance of the required class using a constructor that takes a String (the string that was passed in). Change its body to create an instance according to your requirements.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112725&siteId=1