我需要确保类中的方法仅由不同包中选定的方法执行。
package myApp.security;
public class SecurityStuff{
public static final SecurityStuff security = new SecurityStuff();
public KeyStore getKeyStore(){
//if invoked by MySock.getTLSServerSocket()
return keyStore;
//if not, should return null
}
}
package myApp.socks;
public class MySock{
public void getTLSServerSocket(){
KeyStore keyStore = SecurityStuff.security.getKeyStore();
}
}
对于上面的 2 个类,如何确保 SecurityStuff.getKeyStore()
会返回 KeyStore
(如果它来 self 允许的类和方法)?
请考虑到该 jar 稍后会被混淆。
最佳答案
您可以请求发件人的对象:
public KeyStore getKeyStore(Object obj){
if (!obj instanceof MyClassThatIsAllowedToCall) return;
//execute code
}
当您调用 getKeyStore 时,始终提供参数:
getKeyStore(this);
这似乎是您想要的,但它不安全!您可以轻松伪造发件人。因此,如果您实际上要处理 secret 数据,这不是正确的选择。
关于java - 确保方法只能由选定的方法执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47119768/