反思:为什么会有类似setAccessible()的方法? [英] Reflection: Why are there methods like setAccessible()?

查看:199
本文介绍了反思:为什么会有类似setAccessible()的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道,为什么发明Java的人会编写诸如setAccessible(boolean flag)之类的方法,而这些方法使访问修饰符(特别是私有的)变得无用,并且无法保护字段,方法和构造函数免于被访问?看下面的简单示例:

Just wondering, why did the people who invented Java write methods like setAccessible(boolean flag), which makes the access-modifiers (specially private) useless and cannot protect fields, methods, and constructors from being reached? Look at the following simple example:

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

推荐答案

因为某些代码是受信任的代码-即,如果本地应用程序想要这样做,那么可能没什么大不了的.但是,对于不受信任的代码-例如,applet或Web启动应用程序,RMI存根或任何其他下载的代码-都有一个SecurityManager,该代码(通常基于策略文件),可以说对不起,查理",并拒绝setAccessible()请求.

Because some code is trusted code -- i.e., if a local application wants to do this, maybe it's not a big deal. For untrusted code, though -- i.e., an applet, or a web start application, or RMI stubs, or any other downloaded code -- there's a SecurityManager in place, which (generally based on a policy file) has the opportunity to say "Sorry, Charlie" and deny the setAccessible() request.

这篇关于反思:为什么会有类似setAccessible()的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆