gpt4 book ai didi

java - 反射(reflection):为什么会有setAccessible()这样的方法?

转载 作者:搜寻专家 更新时间:2023-11-01 01:45:25 26 4
gpt4 key购买 nike

只是奇怪,为什么发明Java的人要写setAccessible(boolean flag)这样的方法,这使得访问修饰符(特别是private)变得毫无用处,无法保护字段、方法和构造函数免受攻击被达到?请看下面的简单示例:

public class BankAccount
{
private double balance = 100.0;

public boolean withdrawCash(double cash)
{
if(cash <= balance)
{
balance -= cash;
System.out.println("You have withdrawn " + cash + " dollars! The new balance is: " + balance);
return true;
}
else System.out.println("Sorry, your balance (" + balance + ") is less than what you have requested (" + cash + ")!");
return false;
}
}

import java.lang.reflect.Field;

public class Test
{
public static void main(String[] args) throws Exception
{
BankAccount myAccount = new BankAccount();
myAccount.withdrawCash(150);

Field f = BankAccount.class.getDeclaredFields()[0];
f.setAccessible(true);
f.set(myAccount, 1000000); // I am a millionaire now ;)

myAccount.withdrawCash(500000);
}
}

输出:

Sorry, your balance (100.0) is less than what you have requested
(150.0)! You have withdrawn 500000.0 dollars! The new balance is: 500000.0

最佳答案

因为某些代码是可信代码——也就是说,如果本地应用程序想要这样做,也许这没什么大不了的。对于不受信任的代码,虽然 - 即小程序、Web 启动应用程序、RMI stub 或任何其他下载的代码 - 有一个 SecurityManager,它(通常基于策略文件)有机会说“对不起,查理”并拒绝 setAccessible() 请求。

关于java - 反射(reflection):为什么会有setAccessible()这样的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12237565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com