简体   繁体   中英

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 :

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 ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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