Get “real” class of generic type

前端 未结 5 687
傲寒
傲寒 2021-02-02 16:33

How can I get the \"real\" class of a generic type?

For Example:

public class MyClass {
    public void method(){
        //something

        S         


        
5条回答
  •  孤街浪徒
    2021-02-02 17:29

    As others have explained, you cannot do it in that fashion but this is how it's usually achieved in java.

    public class MyClass {
        public void method(Class clazz) {
            // something
    
            System.out.println(clazz.getName());
    
            // something
        }
    }
    

    and you use it like this

    new MyClass().method(String.class);
    

提交回复
热议问题