为什么会反映在Java和.NET调用(不那么)私有方法 [英] Why can you reflect and call a (not so) private method in Java and .Net

查看:203
本文介绍了为什么会反映在Java和.NET调用(不那么)私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java和C#也可以调用通过反射的私有方法(如下图所示)。

In both Java and C# it is possible to invoke a private method via reflection (as shown below).


  • 这是为什么允许?

  • 什么是这样做的后果?

  • 如果它被带走的语言的未来版本?

  • 请其他语言/平台允许这样做?如果我有这个类在两个Java和C#

  • Why is this allowed?
  • What are the ramifications of doing this?
  • Should it be taken away in a future version of the language?
  • Do other languages/platforms allow this?If I have this class in both Java and C#

下面是例子

public class Foo
{
    private void say() { WriteToConsoleMethod("Hello reflected world"); }
}



其中, WriteToConsole()是特定语言,那么我可以运行以下命令以调用私有说()方法:

where WriteToConsole() is language specific, then I can run the following to call the private say() method:

< STRONG> C#

Foo f = new Foo();
var fooType = f.GetType();
var mi = fooType.GetMethod("say", BindingFlags.NonPublic | BindingFlags.Instance);
mi.Invoke(f, null);



的Java

Foo f = new Foo();
Method method = f.getClass().getDeclaredMethod("say", null);
method.setAccessible(true);
method.invoke(f, null);



正如你所看到的,它并不明显,但也不是没有困难的。

As you can see, it is not obvious, but it's not difficult either.

推荐答案

在Java和.NET,如果你有足够的权限,这是只允许。你直接在命令行中运行代码(通常)在完全信任方式运行。如果您尝试在更严格的环境中做同样的事情,它会失败。访问控制是更多的封装安全性比不过。如果你在完全信任操作,你可能已经得到足够的访问,推出本地方法闲逛内存直接反正...

In both Java and .NET, this is only allowed if you have sufficient permissions. Code that you run directly from the command line is (usually) operating in "full trust" mode. If you try doing the same thing in more restrictive environments, it will fail. Access control is more about encapsulation than security though. If you're operating at full trust, you've probably got enough access to launch native methods to poke around memory directly anyway...


  • 为什么不允许?的有时,它都能得心应手。应该小心对待,但它可能是有用的。

  • Why is it allowed? Sometimes it can be handy. It should be treated with care, but it can be useful.

什么后果的你的代码变得脆弱。?;你在某种程度上,它并不指望一个类型进行交互。

What are the ramifications? Your code becomes fragile; you're interacting with a type in a way it doesn't expect.

如果它在语言的未来版本中被带走? 的它是一个平台的功能,而不是摆在首位的语言功能,但不,我不认为它应该被删除。

Should it be taken away in a future version of the language? It's a platform feature rather than a language feature in the first place, but no I don't think it should be removed.

做其他语言/平台允许这样做?的我不知道......我不会感到惊讶,虽然。

Do other languages/platforms allow this? I'm not sure... I wouldn't be surprised though.

这篇关于为什么会反映在Java和.NET调用(不那么)私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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