亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java如何避免將Class作為泛型對象的參數傳遞

Java如何避免將Class作為泛型對象的參數傳遞

翻閱古今 2021-12-10 10:23:40
我寫了以下內容:public class DataContainer<Data>{    public DataContainer(Class<Data> clazz, String method) throws NoSuchMethodException, SecurityException{        clazz.getMethod(method);    }}所以我以這種方式創建我的對象:new DataContainer<SomeClass>(SomeClass.class, "get");但我希望它看起來更像:public class DataContainer<Data>{    public DataContainer(String method) throws NoSuchMethodException, SecurityException{        Data.getMethod(method);    }}構造調用應如下所示:new DataContainer<SomeClass>("get");Data在構造 ADataContainer對象時如何避免傳遞類?我知道Data不能在運行時操作(new DataContainer<>("get");-> 那什么是數據?)但我聽說有解決方案可以解決,不幸的是,我似乎還沒有用 google 搜索它。這也是我的問題的簡化版本,我們假設方法是有效的、公共的并且沒有參數。
查看完整描述

1 回答

?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

由于類型擦除,您想要使用代碼的方式實際上是不可能的。


然而,一些通用信息在運行時被保留,即當它可以被反射訪問時。一種這樣的情況是類層次結構上的泛型,即你可以做這樣的事情(我們經常這樣做):


//Note that I used T instead of Data to reduce confusion

//Data looks a lot like an actual class name

public abstract class DataContainer<T>{

  public DataContainer(String method) throws NoSuchMethodException, SecurityException {

    Class<?> actualClass = getActualTypeForT();

    //use reflection to get the method from actualClass and call it

  }


  protected Class<?> getActualTypeForT() {

    //get the generic boundary here, for details check http://www.artima.com/weblogs/viewpost.jsp?thread=208860

  } 


//A concrete subclass to provide the actual type of T for reflection, can be mostly empty

public class SomeClassContainer extends DataContainer<SomeClass> {

  //constructor etc.

}

類字段或參數應該有類似的東西,盡管我沒有測試過。由于類型擦除,您想要使用代碼的方式實際上是不可能的。


然而,一些通用信息在運行時被保留,即當它可以被反射訪問時。一種這樣的情況是類層次結構上的泛型,即你可以做這樣的事情(我們經常這樣做):


//Note that I used T instead of Data to reduce confusion

//Data looks a lot like an actual class name

public abstract class DataContainer<T>{

  public DataContainer(String method) throws NoSuchMethodException, SecurityException {

    Class<?> actualClass = getActualTypeForT();

    //use reflection to get the method from actualClass and call it

  }


  protected Class<?> getActualTypeForT() {

    //get the generic boundary here, for details check http://www.artima.com/weblogs/viewpost.jsp?thread=208860

  } 


//A concrete subclass to provide the actual type of T for reflection, can be mostly empty

public class SomeClassContainer extends DataContainer<SomeClass> {

  //constructor etc.

}

類字段或參數應該有類似的東西,盡管我沒有測試過。


查看完整回答
反對 回復 2021-12-10
  • 1 回答
  • 0 關注
  • 312 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號