I think if you want to be extreme, you can get a stack trace as follows:
public class Bar {
I put together a simple script in which it checks if the second instance that calls the class is the same object or something else.
public class StackTraceTest { private void execute() { try { throw new Exception(); } catch (Exception e) { if(!e.getStackTrace()[1].getFileName().equals(StackTraceTest.class.getSimpleName() + ".java")) { throw new IllegalAccessError("Illegal Access."); } } } public void executeExternal() { this.execute(); } }
and
public class AccsessorTest { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { StackTraceTest stackTraceTest = new StackTraceTest(); stackTraceTest.executeExternal(); System.out.println("Accessed from within other method in class."); System.out.println(""); Class<?> clazz = StackTraceTest.class; Method method = clazz.getDeclaredMethod("execute"); method.setAccessible(true); System.out.println("Accessing through reflection..."); method.invoke(stackTraceTest); } }
Then i get
Accessed from within other method in class. Reflection test start. Accessing through reflection... Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at stacktracetest.another.AccsessorTest.main(AccsessorTest.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134) Caused by: java.lang.IllegalAccessError: Illegal Access. at stacktracetest.StackTraceTest.execute(StackTraceTest.java:18) ... 10 more
So, I think you can check with the magic of the stack trace element, but you have to check if this really works, this is very rude, and I just compiled it a second time.
source share