UPDATE: My question is not related with Instantiate enum class. That question just needs to instantiate the enum with one of the existing values. I am asking: why the Reflection API throws NoSuchMethodException
for a method that really exists?.
The following code runs without error, or not, depending on whether Xpto
is declared as class
or enum
.
class Xpto {
// Bar; // include this for enum declaration
private Xpto() {
}
}
public class App {
public static void main(String[] args) throws Exception{
Constructor<Xpto> constructor = Xpto.class.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance();
}
}
In both cases javap
shows a constructor private Xpto()
. If Xpto
is a class then the result of javap -private
is:
class Xpto {
private Xpto();
}
If Xpto
is a enum then the result of javap -private
is:
final class Xpto extends java.lang.Enum<Xpto> {
...
private Xpto();
static {};
}
Yet for latter it throws an exception:
Exception in thread "main" java.lang.NoSuchMethodException: Xpto.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
In both cases the result of the compilation is a class with a private constructor. The use of the reflection API in Xpto.class.getDeclaredConstructor();
does not report an error regarding the fact of Xpto
being a enum, ot not. It just throws that there is no such method Xpto.<init>()
for the case of a enum. This is not true. Because that constructor exists.