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网络共享原来如此简单,WiFi共享精灵开启半天都弱爆了!
    JQUERY UI Datepicker Demo
    Official online document, install svn server in centOS
    JAVE not work in linux
    AMR 转mp3 失败
    XD, XR, DR 股票
    Linux 下MySql 重置密码
    Difinition Of Done
    Apache, Tomcat, JK Configuration Example
    Linux 安装tomcat
  • 原文地址:https://www.cnblogs.com/eustoma/p/10151227.html
Copyright © 2011-2022 走看看