特定于类的方法可见性 [英] Class-specific method visibility

查看:124
本文介绍了特定于类的方法可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一些面向对象的东西,您可以从某些类中调用某些方法,但不是全部?有没有类似受受保护的的东西?

Is there some object oriented thing that you can call some methods from certain classes, but not all of them? Is there something like that which is similiar to protected?

说您有方法 void foo(),并且您希望它可以在几种类型类中供程序员使用(也许类似使用Type变量(用于指定: T type )。现在,也许有某种方法,而不必继承其中带有 foo()的类或创建接口以指定哪些类或类的类型可以访问该方法?

Say you have a method void foo() and you want it to be available to the programmer in a few types of classes (perhaps something like using Type variables (to specify: T type). Now, perhaps is there some way, without inheriting the class with foo() in it, or making an interface, to specify which classes or types of classes have access to that method?

我想这可能像多重继承和多态性吗?类来访问方法而不更改方法的可见性。我希望可见性是特定于类的。

I would guess this could be like multiple-inheritance and polymorphism? But I still want only the class and certain classes to access the method without changing the visibility of the method. I want the visibility to be class-specific.

这里是一个示例:

A类 foo()视为私有,但只有该类将其视为

B类 foo()视为公共/受保护的,但只有该类看到

class A sees foo() as private, but only that class sees it as private.
class B sees foo() as public/protected, but only that class sees it as public.

方法类型为 default

我想更容易提出和回答的是:是否存在特定于类的可见性?

I guess what is easier to ask and answer to is: "Is there class-specific visibility?"

推荐答案

在C ++中,您可能需要一些类似的东西,它称为朋友类。但是,Java不支持该概念:

There is something like you are asking for in C++, it is called friend classes. Nevertheless, that concept is not supported by Java:

朋友是否等效于Java?

第二种选择是使用代码反射来访问类的私有成员,但这不是一个干净的解决方案并且仅适用于受保护的元素:

A second option is to use code reflection to access a class private members but it isn't such a clean solution and only works for protected elements:

public class C1 {

    public C1()
    {
        x = "Hello Word!";
    }

    protected String x;
}

在另一种方法下:

String val = (String)obj.getClass().getDeclaredField("x").get(obj);
System.out.println("val: " + val);

编辑:经过一些研究,我发现有可能甚至访问私有成员:

After making a little bit of research I found it is possible even to access private members:

Field field = obj.getClass().getDeclaredField("x");
field.setAccessible(true);
String val = (String)field.get(obj);
field.setAccessible(false);

这篇关于特定于类的方法可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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