Example: Using the method doCoolStuff() from class PrivateCoolClass

Here’s a piece of code using the Java Reflection API:

try {

Class clazz = Class.forName("com.framework.PrivateCoolClass");

Constructor constructor = clazz.getConstructor(String.class);

Object object = constructor.newInstance("Super");

Method method = clazz.getMethod("doCollStuff", int.class);

Object result = method.invoke(object, 42);

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (NoSuchMethodException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}

All exceptions could be caught in one statement but you get the idea. It’s barely readable, all the reflection gets in the way of what you are trying to achieve and you have to remember how to use it every time.

With Mirror, the reflection API is totally invisible. First, we need to declare an interface that will represent the Java class we want to use:

@Class("com.framework.PrivateCoolClass")

public interface CoolClass {

@Constructor void callConstructor(String name);

String doCoolStuff(int value);

}

Some explanations here:

The private class is specified by the @Class annotation.

annotation. As we need to retrieve an instance of the private class at some point, we need a method annotated with @Constructor and the same signature as an existing constructor.

a method annotated with and the same signature as an existing constructor. Other methods are declared with the exact same signature as the private class.

Once this is done, we are able to do the exact same things as the code above with only a few lines of code:

try {

CoolClass coolClass = Mirror.create(CoolClass.class);

coolClass.callConstructor("Super");

String result = coolClass.doCoolStuff(42);

} catch (MirrorException e) {

e.printStackTrace();

}

If you’d like more information on feature and capabilities, please check the README.

Download

Mirror is available on Jcenter! If you are using Gradle add this line to the dependencies of your module: