[英]Invoke static method dynamically without using reflection
說我有這樣的事情:
public class Entity<T> {
public Class<T> model;
public Entity(Class<T> m){
this.model = m;
}
}
所以我們像這樣使用它:
var ent = new Entity<String>(String.class);
但我不能打電話給:
ent.model.format()
要么
ent.model.join()
等等。在這種情況下,沒有靜態方法可用。 有沒有一種方法可以在不使用反射的情況下調用這些靜態方法?
似乎您想將類型綁定到Entity
類中的屬性,理想情況下,您可以按照以下方法進行操作:
class Entity<T> {
public T model;
public Entity(T m) {
this.model = m;
}
}
然后可以實例化為:
var ent = new Entity<>(""); // T is inferred based on the attribute type in the c'tor call
// or also explicitly specified as
var ent = new Entity<String>(""); //redundant though
然后將其進一步用作:
ent.model.format(""); // in this example 'model' is a 'String' with empty value ""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.