0


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!

phenomax
  • 35
  • 5
  • Just asked the same question :) http://stackoverflow.com/questions/31983540/creating-an-instance-for-class/31983719#31983719 – Suresh Atta Aug 13 '15 at 10:02
  • 1
    It would help if you'd provide a short but complete program that demonstrates the problem. As far as I'm aware, `class.class` isn't valid syntax, for example. What *exactly* are you trying to do, and what does this have to do with enums? – Jon Skeet Aug 13 '15 at 10:03

2 Answers2

1

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);
Karthik R
  • 5,523
  • 2
  • 18
  • 30
1

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.

Community
  • 1
  • 1
Dennis Hunziker
  • 1,293
  • 10
  • 19