Java – how to restrict method calls to specific methods

I have a special requirement. I need to ensure that only specific methods in one class are allowed to call public (non static) methods from the second class Inheritance cannot be used

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 normally, but due to the quality control in code audit, I need to propose another (or more accurately) better solution Is there a better way to achieve this goal?

Solution

One way to improve the method is that you don't need to create an exception to get the stack trace. You can use the thread method

StackTraceElement[] stack = Thread.currentThread().getStackTrace();

Maybe you want to use this class instead of a handwritten 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");
}

Besides, I don't know how to do this better without changing logic or inheritance

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>