1

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?

Lena Bru
  • 13,521
  • 11
  • 61
  • 126

2 Answers2

10

You need a parameter of type Class<?>:

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

You should go through Reflection Tutorial

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

Do you mean something like this:

  public <T> void MyFunction(Class<T> something1, SomeOtherType  something2){
  // T= type parameter inside method
  }
Shamim Ahmmed
  • 8,265
  • 6
  • 25
  • 36