1 回答

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.
}
類字段或參數應該有類似的東西,盡管我沒有測試過。
添加回答
舉報