Home > Java > javaTutorial > body text

Can Java Reflection Access Private Fields?

Patricia Arquette
Release: 2024-10-28 06:02:02
Original
524 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!