Abstract :
I have a private class (Deque) that I need to create an object of, from another class outside of the package (package com.example)
package com.example;
final class Deque {
public Deque() {}
}
Using reflection, how would I go about creating an object of Type com.example.Deque, from a class that is not inside the package com.example?
Stephan Hogenboom :
It is tricky and usually not recommended to do so, but you can create and object of Deque
outside the package. I am not aware if you can have a proper reference of the type Deque to it though.
package com.demo;
final class NotADeque {
public NotADeque() {}
public static void main(String[] args) throws ClassNotFoundException,
NoSuchMethodException, IllegalAccessException, InvocationTargetException,
InstantiationException {
Class<?> c = Class.forName("com.example.Deque");
Constructor<?> constructor = c.getDeclaredConstructor();
constructor.setAccessible(true);//Make the constructor accessible.
Object o = constructor.newInstance();
System.out.println(o);
}
}
This will create an instance of Deque
, but with an Object
reference to it. Also look at the amount of checked exceptions that might be thrown while doing this, this is a very flimsy approach. For more details check this question