Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection isAccessible method

I'm learning reflection. When I execute the following code:

package main;

import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) throws NoSuchFieldException, SecurityException {

        Base firstBase = new Base();
        Field firstBaseField = firstBase.getClass().getDeclaredField("protectedBuffer");
        System.out.println(firstBaseField.isAccessible());

    }
}

This is Base class:

package main;

public class Base {

    private StringBuffer buffer;
    protected StringBuffer protectedBuffer;
    public StringBuffer buffer2;

}

the result is false. But shoudn't it be true, because I can access protectedBuffer in this way: firstBase.protectedBuffer?

like image 544
DPM Avatar asked Aug 15 '15 11:08

DPM


People also ask

What is reflection method in Java?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

How do you implement reflection in Java?

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");

What can I use instead of reflection in Java?

The alternate for reflection is using Interface. Just taking from Effective Java by Joshua Bloch. We can obtain many of the benefits of reflection while incurring few of its costs by using it only in a very limited form.

Is reflection faster Java?

Adding setAccessible(true) call makes these reflection calls faster, but even then it takes 5.5 nanoseconds per call. Reflection is 104% slower than direct access (so about twice as slow). It also takes longer to warm up.


1 Answers

As of Java 9 the isAccessible method is deprecated. You can use canAccess instead.

like image 124
SJX Avatar answered Oct 05 '22 00:10

SJX