zoukankan      html  css  js  c++  java
  • 利用ParameterizedType获取泛型参数类型

    https://www.cnblogs.com/baiqiantao/p/5373283.html

    GenericsDemo.java

     1 import java.lang.reflect.ParameterizedType;
     2 import java.lang.reflect.Type;
     3 
     4 //利用ParameterizedType获取java泛型的参数类型
     5 
     6 public class GenericsDemo {
     7     public static void main(String[] args) {
     8         classTest();
     9         interfaceTest();
    10     }
    11     
    12     private static void classTest() {
    13         MySuperClass<Student, String> mySuperClass = new MySuperClass<Student, String>() {
    14             @Override
    15             public void onSuccess(Student data) {
    16             }
    17         };
    18         //getClass().getGenericSuperclass()返回表示此 Class 所表示的实体的直接超类的 Type
    19         ParameterizedType type = (ParameterizedType) mySuperClass.getClass().getGenericSuperclass();
    20         sysoType(type);
    21     }
    22     
    23     private static void interfaceTest() {
    24         MyInterface<Student, String> myInterface = new MyInterface<Student, String>() {
    25             @Override
    26             public void onSuccess(Student data) {
    27             }
    28         };
    29         ParameterizedType type = (ParameterizedType) myInterface.getClass().getGenericInterfaces()[0];
    30         sysoType(type);
    31     }
    32     
    33     private static void sysoType(ParameterizedType type) {
    34         System.out.println(type + "
    " + type.getClass());
    35         
    36         //返回表示此类型实际类型参数的 Type 对象的数组,泛型的参数可能有多个,我们需要哪个就取哪个
    37         Type[] targets = type.getActualTypeArguments();
    38         for (int i = 0; i < targets.length; i++) {
    39             System.out.println(targets[i] + "
    " + targets[i].getClass());
    40         }
    41     }
    42 }

    MyInterface.java

    1 public interface MyInterface<T, V> {
    2     void onSuccess(T data);
    3 }

    MySuperClass.java

    1 public abstract class MySuperClass<T,V> {
    2     public abstract void onSuccess(T data);
    3 }

    Student.java

    1 public class Student {
    2 
    3 }

     GenericsDemo.rar

  • 相关阅读:
    win7下设置smtp的方法
    win7下怎么安装IIS
    python语法笔记(二)
    python语法笔记(一)
    python 的类变量和对象变量
    mysql使用笔记(四)
    mysql使用笔记(三)
    mysql使用笔记(二)
    windows下重新安装TCP/IP协议栈
    c++程序编码
  • 原文地址:https://www.cnblogs.com/eustoma/p/10151227.html
Copyright © 2011-2022 走看看