简体   繁体   中英

Instantiate a class - java


I have an enum class with the params id and Class.

ENUM1(1, class.class);

private int id;
private Class<?> clazz;

ENUM(int id, Class<?> clazz) {
    this.id = id;
    this.clazz = clazz;

}

The class implements an abstract interface.
But how can i access the public methods of the "class.class"?

Thanks in advance!

You can do this following from the Class using reflection API.

Object obj = object.getClass().newInstance();//instantiates using default constructor provided that there are no checked exceptions thrown. Consider `Constructor` instead
object.getClass().getDeclaredMethod("ImPublicMethodName", param1, param2).invoke(object);

Considering Why is Class.newInstance() "evil"? I'd use something like:

    Constructor<?> ctor = clazz.getDeclaredConstructor();
    Object obj = ctor.newInstance();
    Method method = clazz.getDeclaredMethod("yourMethod");
    method.invoke(obj);

The getDeclaredXZY methods optionally take the types of arguments as well.

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