简体   繁体   English

在Java中编写需要Class.class作为参数的函数

[英]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 我想编写一个需要Class.class作为参数的函数

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? 我想实现这种类型的调用,如何定义“ MyFunction”以接受这种类型的参数?

what should be instead of "whatTypeGoesHere"? 应该是什么而不是“ 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 我想使用GSON从JSON反序列化类,但是我发现自己要在每个要反序列化的类中编写完全相同的方法,但要使用类名的不同

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 我想将“ fromJSON”方法放到一些utils类中,因为在每个类中它都是完全一样的,只是返回的类名不同

how do i do that? 我怎么做?

You need a parameter of type Class<?> : 您需要一个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
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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