Code Patterns

Copy-paste examples for common plugin tasks. Commands, events, ECS, GUI, and more.

← Back to Patterns
util

Reflection Field Access

Access private fields via reflection

Example Code

java
public class ReflectionUtil {
    @SuppressWarnings("unchecked")
    public static <T> T getField(Class<T> classZ, Object object, String fieldName) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return (T) field.get(object);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}

// Usage:
String value = ReflectionUtil.getField(String.class, someObject, "privateFieldName");