简体   繁体   English

动态调用静态方法而不使用反射

[英]Invoke static method dynamically without using reflection

Say I have something like so: 说我有这样的事情:

public class Entity<T> {

  public Class<T> model;

  public Entity(Class<T> m){
    this.model = m;
  }

}

so we use it like: 所以我们像这样使用它:

var ent = new Entity<String>(String.class);

but I can't call: 但我不能打电话给:

ent.model.format() 

or 要么

ent.model.join()

etc. None of the static methods are available in this case. 等等。在这种情况下,没有静态方法可用。 Is there a way to call these static methods without using reflection? 有没有一种方法可以在不使用反射的情况下调用这些静态方法?

Seems like you want to bind the type to the attribute in your Entity class, for which you can ideally follow the approach as : 似乎您想将类型绑定到Entity类中的属性,理想情况下,您可以按照以下方法进行操作:

class Entity<T> {
    public T model;
    public Entity(T m) {
        this.model = m;
    }
}

which can then be instantiated as : 然后可以实例化为:

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 

and then use it further as : 然后将其进一步用作:

ent.model.format(""); // in this example 'model' is a 'String' with empty value ""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM