I tested your code and its working fine. But i was also able to reproduce your issue.
Assuming, you are calling
factoryMethod(MyClass.class);
Then, if the class "MyClass" is inside its OWN Classfile its working fine with just providing
concreteClass.newInstance();
When having the implementation of the class as a inner Class Type, the Class not found exception is thrown.
The reason is, that a inner class is actually a type of a nested class, and therefore creating a instance is only possible, when working with the enclosing Class, also.
In the example given bellow, the newInstance()
method has been used along with an inner class.
public class Test {
public class MyClass implements MyInterface {
}
public interface MyInterface {
}
public static void main(String[] args){
MyInterface ret = method(MyClass.class);
if (ret instanceof MyClass){
System.out.println("Is MyClass");
}
}
public static MyInterface method(Class<? extends MyInterface> actualClass){
try {
Class<?> enclosingClass = Class.forName(actualClass.getDeclaringClass().getCanonicalName());
Object enclosingInstance = enclosingClass.newInstance();
Class<?> innerClass = Class.forName(actualClass.getName());
Constructor<?> constructor = innerClass.getDeclaredConstructor(enclosingClass);
Object innerInstance = constructor.newInstance(enclosingInstance);
return (MyInterface) innerInstance;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}