Can I limit the methods another class can call in Java?

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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; } } 

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

回答1:

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.



回答2:

Yes it is, but you have to go through some gyrations.

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

Now when you define the method in A that receives a reference to a B instance, define that method to take an Incrementable instead. For B, define it to take a Readable.



回答3:

Java has 4 scopes: private, protected, public and "package". Something that is public can be accessed from anywhere. protected only from subclasses. private is only that class. "package" scope is not named, but if you omit any of the other three, it is assumed package scope. This is only accessible by other classes in the same package.

HTH.



回答4:

No it is not possible to do that.



回答5:

Not that you'd want to, but you could go up the stack trace (create an exception) and check the class that's calling your increment method.



回答6:

Although the straight answer is no, another workaround(an ugly one) could be to create two interfaces extending a third(or you could just take an Object as parameter): Reader and Writer, to pass the calling class as a parameter to each function:

public interface Caller; public interface Reader extends Caller; public interface Writer extends Caller;   public void increment(Caller c) {       if (c instanceof Writer) {          i++;      }  } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!