我可以限制另一个类可以在Java中调用的方法吗? [英] Can I limit the methods another class can call in Java?

查看:325
本文介绍了我可以限制另一个类可以在Java中调用的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设我有类 A B C 其中class C 具有可读写属性:

Let's assume I have classes A, B, and C where class C has readable and writable properties:

public class C {
    private int i = 0;

    // Writable.
    public void increment() { i++; }

    // Readable.
    public int getScore() { return i; }
}

是否可以只让 A 使用 increment()方法,只让 B 使用 getScore ()方法?

Is it possible to only let A use the increment() method and only let B use the getScore() method?

推荐答案

不,不能分配每类访问权限。



考虑将您的类分成单独的接口,以便每个类只获得一个具有所需接口的对象。例如:

No, it is not possible to assign per-class access.

Consider separating your class into separate interfaces so that each class only gets an object with the interface it needs. For example:

interface Incrementable { public void increment(); }
interface HasScore { public int getScore(); }
class C implements Incrementable, HasScore { /* ... */ }

class A {
  public A(Incrementable incr) { /* ... */ }
}

class B {
  public B(HasScore hs) { /* ... */ }
}

当然,有安全隐患,但这应该让你思考正确的方向。

Of course, there are security implications but this should get you thinking in the right direction.

这篇关于我可以限制另一个类可以在Java中调用的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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