Java-如何限制从特定方法进行的方法调用 [英] Java - How to restrict method calling from a specific method
问题描述
我有一个特殊的要求,即我需要确保只允许一个类中的特定方法调用第二个类中的公共(非静态)方法.不能使用继承.
I have a peculiar requirement where I need ensure that only a particular method from one class is allowed to call a public (non-static) method from a second class. Inheritance cannot be used.
一种选择是如下使用StackTrace:
One option is to use StackTrace as follows:
ClassA.java
package org.rnd.stack;
public class ClassA {
public void methodA() throws IllegalAccessException {
Exception fake = new Exception("FAKE-IGNORE");
StackTraceElement[] stack = fake.getStackTrace();
StackTraceElement st = stack[1];
if ("org.rnd.stack.ClassB".equals(st.getClassName())
&& "methodB".equals(st.getMethodName())) {
System.out.println("You are allowed to call");
} else {
throw new IllegalAccessException("You are not allowed to call");
}
}
}
ClassB.java
package org.rnd.stack;
public class ClassB {
public void methodB() throws IllegalAccessException {
new ClassA().methodA();
}
public void illegalMethod() throws IllegalAccessException {
new ClassA().methodA();
}
public static void main(String[] args) {
try {
new ClassB().methodB();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
现在,上述解决方案可以正常工作,但是由于代码审核中的质量控制,我需要提出另一个(或更确切地说)更好的解决方案.有没有更好的方法来实现这一目标?
Now the above solution works fine, but due to quality control in code audit I need to come up with another (or rather) better solution. Is there a better way to achieve this?
推荐答案
一种改进方法的方法是,您无需创建异常即可获取堆栈跟踪,可以使用线程方法.
A way to improve you method is that you don't need to create an exception to get the stacktrace, you can use the thread methods.
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
也许您也想使用类而不是手写包.例如:
Also maybe you want to use the class instead of handwriting the package. For example:
if (ClassB.class.getName().equals(st.getClassName())
&& "methodB".equals(st.getMethodName())) {
System.out.println("You are allowed to call");
} else {
throw new IllegalAccessException("You are not allowed to call");
}
除此之外,我不知道如何在不更改逻辑或使用继承的情况下更好地做到这一点.
Apart from that I don't know how you can do it better without changing your logic or using inheritance.
这篇关于Java-如何限制从特定方法进行的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!