简体   繁体   English

实例化一个类-Java

[英]Instantiate a class - java


I have an enum class with the params id and Class. 我有一个带有参数id和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"? 但是,如何访问“ class.class”的公共方法?

Thanks in advance! 提前致谢!

You can do this following from the Class using reflection API. 您可以使用反射API从Class执行以下操作。

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"? 考虑为什么Class.newInstance()是“邪恶的”? 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. getDeclaredXZY方法还可以选择采用参数的类型。

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

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