首页 > 解决方案 > 如何为 Java 类传递参数 T

问题描述

如何为方法 reciveClassTest(Class clazz) 传递参数

下面是一个类的示例,它们很好地代表了 withType 没有类型 Paper 的场景

public class TestPassClassType {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    TestPassClassType call=new TestPassClassType();
    
    Paper paper=new Paper();
    System.out.println(paper);
    
    MyType<Paper> type=new MyType<Paper>();
    
    System.out.println(type);
    
    // How to pass  call.reciveClassTest(MyType<Paper>.class)
    call.reciveClassTest(MyType.class);

    }

    public <T> void reciveClassTest(Class<T> clazz) throws InstantiationException, IllegalAccessException {
    
    T t=clazz.newInstance();
    MyType<Paper> withType=(MyType<Paper>) t;
    
    //withType not has a type Paper
    System.out.println(withType);
    }
}

class MyType<T> {
    
    public MyType() {}

    T data;

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

class Paper implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

标签: javajacksonjackson-databind

解决方案


推荐阅读