Skip to content

Examples

Frank van der Heijden edited this page Dec 21, 2020 · 1 revision

Examples

You can use any class available at runtime to use reflections on. For example, you could create a reflections object for the CraftServer object:

public class RCraftServer {

    private static final MinecraftReflection reflection = MinecraftReflection
            .of("org.bukkit.craftbukkit.%s.CraftServer");

    public static MinecraftReflection getReflection() {
        return reflection;
    }
}

Fields

To get a field from a class, you should use the following format:

Reflection#get(Object instance, String field)

With the above, you can achieve something like this:

public class RCraftServer {
    ...
    public static SimpleCommandMap getCommandMap() {
        return reflection.get(Bukkit.getServer(), "commandMap");
    }

Methods

To get a method, there are two methods you can use:

Reflection#invoke(Object instance, String method, Object... parameters)

and:

Reflection#invoke(Object instance, String method, ClassObject<?>... parameters)

A ClassObject is useful instead of the actual parameter if the method's parameter types are different from the one you put in. For example, take the following method:

public void doSomething(boolean bool) {
    ...
}

The above method can't just be called with the first invoke method: since the reflection library will search for a method with the class Boolean.class (the boolean parameter supplied is casted to an Object, calling getClass() on that object results in java.lang.Boolean), and Boolean.class ≠ boolean.class! You need to use the second invoke method:

Reflection reflection = MinecraftReflection.of(...);
Object instance = ...;
reflection.invoke(instance, "doSomething", ClassObject.of(boolean.class, false));

Constructors

Constructors essentially have the same way of being called as methods:

Reflection#newInstance(Object... parameters)

and:

Reflection#newInstance(ClassObject<?>... classObjects)

Clone this wiki locally