make Field and Method Accessible during reflection - Java Reflection

Java examples for Reflection:Field

Description

make Field and Method Accessible during reflection

Demo Code


//package com.java2s;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Main {
    public static void makeAccessible(Field field) {
        if ((!Modifier.isPublic(field.getModifiers())
                || !Modifier.isPublic(field.getDeclaringClass()
                        .getModifiers()) || Modifier.isFinal(field
                .getModifiers())) && !field.isAccessible()) {
            field.setAccessible(true);//from   w w w.  j  a v a 2s  . com
        }
    }

    public static void makeAccessible(Method method) {
        if ((!Modifier.isPublic(method.getModifiers()) || !Modifier
                .isPublic(method.getDeclaringClass().getModifiers()))
                && !method.isAccessible()) {
            method.setAccessible(true);
        }
    }
}

Related Tutorials