Home  >  Article  >  Java  >  Can Java Reflection Access Private Fields?

Can Java Reflection Access Private Fields?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 06:02:02634browse

Can Java Reflection Access Private Fields?

Accessing Private Fields via Reflection in Java

Question: Can Java's reflection mechanism be used to access private fields, such as the str field in the following code snippet?

<code class="java">public class Test {

   private String str;
   public void setStr(String value) { str = value; }
}</code>

Answer: Yes, it is possible to access private fields via reflection. However, security permissions must be granted and setAccessible(true) must be used when accessing the field from a different class.

Consider the following example:

<code class="java">import java.lang.reflect.*;

public class Other {

    private String str;
    public void setStr(String value) { str = value; }
}

public class Test {

    public static void main(String[] args) throws Exception {

        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}</code>

Note: This practice is generally discouraged as it violates the encapsulation principles set by the original class's author. Validation checks or dependencies on other fields may be bypassed, leading to unpredictable behavior.

The above is the detailed content of Can Java Reflection Access Private Fields?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn