A backport of StackWalker.getCallerClass()/sun.reflect.Reflection.getCallerClass() for Java 1.1 - 1.8 (works on newer JVMs as well).
The library searches for the fastest implementation available on the current JVM and, if nothing is available, falls back to retrieving stack information from Throwable.
API consists of two methods:
getCallerClass()- returns the caller class for the method that called getCallerClass();getCallerClass(int index)- returns the caller class for the method that is index stackframes above the current stackframe (for 1 it returns this class, 2 — same as getCallerClass(), 3 — caller of the caller, etc.).
Usage example:
package com.mycompany;
import com.ydo4ki.callers.Callers;
class MyVerySecretClass {
private static final MyVerySecretClass instance = new MyVerySecretClass();
private MyVerySecretClass() {}
// ... some great functionality ...
public static MyVerySecretClass getInstance() {
if (!Callers.getCallerClass().getName().startsWith("com.mycompany"))
throw new SecurityException("No MyVerySecretClass instances for your package!");
return instance;
}
}For projects using Java 5 and later it is also recommended that you use the @CallerSensitive annotation from com.ydo4ki.callers for methods similar to the one in this example.
This annotation might be useful to prevent obfuscation/optimization tools from altering the call stack in the parts of the code that depend on it.
<dependency>
<groupId>com.ydo4ki</groupId>
<artifactId>Callers</artifactId>
<version>1.3</version>
</dependency>implementation("com.ydo4ki:Callers:1.3")Go to the releases tab and download latest jar
Please note that you are required to have JDKs 1.4, 1.8 and 9+ on your computer to compile this.
- Clone this repository
git clone https://github.com/Y-Sulphuris/Callers.git
cd Callers- Create a file "local.properties" in the repository root and add the paths to your JDKs 1.4 and 1.8 to it:
jdk4.home=path/to/j2sdk1.4.0
jdk8.home=path/to/jdk1.8.0- Run maven build (maven should run on Java 9 or higher):
mvn clean packageAs for where to get JDK 1.4, I'll tactfully refrain from commenting on this.