Java重要技術(24)泛型之使用反射訪問參數化型別

來源:互聯網
上載者:User

標籤:com   int   訪問   exception   static   string   end   name   ase   

 

1.1. 用反射訪問參數化型別

 

使用反射機制可以擷取到一部分參數化型別有關的資訊。

public class GenericParameterTest5 { static  class Base{}static class Generic<T extends Base>{ public T  work( List<T>  list){return  list.get(0);} public T  work( T obj){return obj;}} public static void main(String[] args) {  try {  //public T  work( List<T>  list){Method method1  = Generic.class.getMethod("work", List.class);System.out.println(method1.getParameters()[0].getType()); Type  t1 = method1.getGenericParameterTypes()[0];ParameterizedType  pt = (ParameterizedType)t1;System.out.println("rawtype:" +pt.getRawType()                   + "actualtype:" + pt.getActualTypeArguments()[0].getTypeName()); System.out.println("-------------"); //public T  work( T obj){Method method2  = Generic.class.getMethod("work", Base.class);System.out.println(method2.getParameters()[0].getType()); Type  t2 = method2.getGenericParameterTypes()[0];TypeVariable<?>  tv = (TypeVariable)t2;System.out.println(tv.getTypeName());GenericDeclaration  gd = tv.getGenericDeclaration();System.out.println(gd.getTypeParameters()[0]); } catch (NoSuchMethodException | SecurityException e) {e.printStackTrace();}}}

 

 

運行結果如下:

interface java.util.List

rawtype:interface java.util.Listactualtype:T

-------------

class com.test.javatechnology.genericparameter.GenericParameterTest5$Base

T

T

 

Java重要技術(24)泛型之使用反射訪問參數化型別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.