简体   繁体   中英

writing a function that needs Class.class as a parameter in java

I want to write a function that needs a Class.class as a parameter

example:

class MyObject{


  public whatTypeGoesHer MyFunction(something1, something2){
//do something with parameters
}

}

class MyObject1{
      MyObject object = new MyObject();

       MyObject1 object2 = object.MyFunction(MyObject1.class,something else);

}

this type of invokation is what i want to achieve, how do i define "MyFunction" to accept this type of parameter?

what should be instead of "whatTypeGoesHere"?

EDIT:

Let me rephrase the question

  1. i want to deserialize classes from JSON using GSON however, i find myself writing the exact same methods in every class i want to deserialize with the difference of the class name

this is my code:

public static User fromJSON(String json, Class<?> className) {
    GsonBuilder builder = new GsonBuilder();
    builder.serializeNulls();
    User g1 = builder.create();
    User user = g1.fromJson(json, className.getClass());
    return user;
}

and its invokation in the used class

User user =   User.fromJSON(json,User.class);

I want to put the "fromJSON" method to some utils class, because in every class it is EXACTLY the same,with the difference of the class name that it returns

how do i do that?

You need a parameter of type Class<?> :

public void myFunction(Class<?> something1, SomeOtherType something2)

You should go through Reflection Tutorial

Do you mean something like this:

  public <T> void MyFunction(Class<T> something1, SomeOtherType  something2){
  // T= type parameter inside method
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM