私有方法真的安全吗? [英] Are private methods really safe?

查看:83
本文介绍了私有方法真的安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中, private 访问修饰符被认为是安全的,因为在类外部不可见。然后外面的世界也不知道这种方法。

In Java the private access modifier consider as safe since it is not visible outside of the class. Then outside world doesn't know about that method either.

但是我认为Java反射可以用来打破这一规则。考虑以下情况:

But I thought Java reflection can use to break this rule. Consider following case:

public class ProtectedPrivacy{

  private String getInfo(){
     return "confidential"; 
  }

}  

现在从另一个班级去获取信息:

Now from another class I am going to get Info:

public class BreakPrivacy{

   public static void main(String[] args) throws Exception {
       ProtectedPrivacy protectedPrivacy = new ProtectedPrivacy();
       Method method = protectedPrivacy.getClass().getDeclaredMethod("getInfo", null);
       method.setAccessible(true);
       Object result = method.invoke(protectedPrivacy);
       System.out.println(result.toString());
   }
} 

此刻,我只是认为仍然可以使用私有方法,因为要执行上述操作,我们必须知道方法名称。但是,如果类中包含由其他人编写的私有方法,那么我们就无法看到它们。

At this moment I just thought still private method safe since to do some thing like above we must know method name. But if class which contain private method written by some one else we don't have visibility of those.

但是由于下面的代码行,我的观点变得无效了。

But my point become invalid since below line of code.

Method method[] = new ProtectedPrivacy().getClass().getDeclaredMethods();

现在,此方法[] 包含所有事情需要做的高于事情。我的问题是,有没有办法避免使用Java反射做这种事情?

Now this method[] contains all the things need to do above thing. My question is, is there a way to avoid this kind of things doing using Java reflection?

我引用了 Java文档来阐明我的问题。

I am quote some point from Java Documentation to clarify my question.


选择访问级别的提示:

Tips on Choosing an Access Level:

如果其他程序员使用您的课程,则要确保不会发生由于滥用而引起的错误
。访问级别可以帮助您做到这一点。使用对特定
成员有意义的
限制性最高的访问级别。除非有充分的理由,否则请使用private。

If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels can help you do this.Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.


推荐答案

这取决于您的意思通过安全。如果您与允许这种事情的安全管理器一起运行,那么可以,您可以通过反射来做各种令人讨厌的事情。但是然后在这种环境中,无论如何都可以修改库以使该方法公开。

It depends on what you mean by "safe". If you're running with a security manager that allows this sort of thing, then yes, you can do all kinds of nasty things with reflection. But then in that kind of environment the library can probably just be modified to make the method public anyway.

在这样的环境中,访问控制实际上是建议-您有效地信任代码可以很好地发挥作用。如果您信任正在运行的代码,则应使用限制性更强的安全管理器。

Access control is effectively "advisory" in an environment like that - you're effectively trusting the code to play nicely. If you don't trust the code you're running, you should use a more restrictive security manager.

这篇关于私有方法真的安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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