简体   繁体   English

从对象锁定方法(Java)

[英]Lock Methods from Object (Java)

i have the following problem. 我有以下问题。

i hava a java class 我有一个Java类

 public class A {
    login()
    getRights()
    methodA()
    methodB()
    methodC()
   }

now i have the following scenario. 现在我有以下情况。 I create an instance of class A. and now i want to check with the login function wheter i'm logged in. If not, the object don't have the rights to call method a, b and c. 我创建了类A的实例。现在,我想使用登录功能检查一下我是否已登录。如果没有,则该对象无权调用方法a,b和c。 After that i want to check with the getRights() function wheter the object have the rights to call the method b and c. 之后,我想使用getRights()函数检查该对象是否有权调用方法b和c。 Is there a smart implementation? 有一个聪明的实现吗? otherwise i have to inherit from class a and overwrite the blocked functions ? 否则我必须从类A继承并覆盖被阻止的函数?

You can call login() before calling methodA(), or you can write a call to login() inside methodA() so that the code inside methodA() can't be run without running login() first. 您可以在调用methodA()之前调用login(),或者可以在methodA()内编写对login()的调用,这样就必须先运行login()才能运行methodA()内的代码。 Then if the object calls methodA() but doesn't return the right value from login() you can throw an exception before going any farther. 然后,如果对象调用methodA()但未从login()返回正确的值,则可以在进一步处理之前引发异常。 Then do the same thing with getRights() inside B and C. 然后使用B和C中的getRights()做同样的事情。

如果调用了方法a,b和c但未登录,则可能引发异常。您只需要使用变量来设置是否已登录,并设置是否引发异常,而getRights仅使用该变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM