以下程序正在访问和修改 SimpleKeyPair
类中声明的名为 privateKey
的私有(private)字段。让我们来看看吧。
package mod;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
final class SimpleKeyPair
{
private String privateKey = "Welcome SimpleKeyPair ";
}
final public class Main
{
public static void main(String[] args)
{
SimpleKeyPair keyPair = new SimpleKeyPair();
Class c = keyPair.getClass();
try
{
Field field = c.getDeclaredField("privateKey"); // gets the reflected object
field.setAccessible(true);
System.out.println("Value of privateKey: " + field.get(keyPair)); // displays “Welcome SimpleKeyPair"
field.set(keyPair, "Welcome PrivateMemberAccessTest"); // modifys the private member varaible
System.out.println("Value of privateKey: " + field.get(keyPair));
}
catch (IllegalArgumentException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
catch (NoSuchFieldException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
catch (SecurityException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<小时/>
在上面的代码中,通过以下语句访问类 SimpleKeyPair
中声明的私有(private)字段 privateKey
并显示在控制台上。
Field field = c.getDeclaredField("privateKey");
field.setAccessible(true);
System.out.println("Value of privateKey: " + field.get(keyPair));
<小时/>
该字段正在被修改,并且该字段的新值正在通过以下语句显示。
field.set(keyPair, "Welcome PrivateMemberAccessTest");
System.out.println("Value of privateKey: " + field.get(keyPair));
<小时/>
程序的实际输出如下。
Value of privateKey: Welcome SimpleKeyPair
Value of privateKey: Welcome PrivateMemberAccessTest
<小时/>
表示在Java中使用反射可以直接访问私有(private)资源。如果是这样,那么在 Java 中将成员声明为 private 本身并不安全,尽管将类成员声明为 private 的目的之一是向外界隐藏它们。 Java中反射的实际用途是什么?
最佳答案
您是正确的,反射可以允许访问类的私有(private)(以及包和 protected )作用域成员。但是,如果您阅读 JavaDocs,您会发现用于获取和调用这些访问器的所有方法在执行请求的操作之前都会执行 SecurityManager 检查。因此,在具有 SecurityManger 的环境中,操作将失败并抛出 SecurityExceptions。
关于java - Java中通过使用反射来访问和修改私有(private)类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8159411/