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
?
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.
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");
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.
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.
As of Java 9 the isAccessible
method is deprecated. You can use canAccess
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With