To restrict the private method from being called by reflection API we have to write a method that will check the caller of the method. If the caller is from any other class than the current class then we have to throw the error.
We can get the caller class from the caller stack of Reflection API.
getCallerClass(0) will return class "sun.reflect.Reflection"
getCallerClass(1) will return class "com.company.main.MainClass" // Same class
getCallerClass(1) will return class "jdk.internal.reflect.NativeConstructorAccessorImpl" // If it is being called from any other calss.
check if caller class of 1 and 3 are not the same then throw exception.
package com.company.main;
public class MainClass {
private MainClass(){
checkCallerClass();
System.out.println("From private constructor");
}
private void checkCallerClass() {
Class self = sun.reflect.Reflection.getCallerClass(1);
Class caller = sun.reflect.Reflection.getCallerClass(3);
if (self != caller) {
throw new java.lang.IllegalAccessError();
}
}
}
No comments:
Post a Comment
Thank You for your valuable comment