Skip to content
SulphurisPublic

About

Small library that gives you access to getCallerClass() for Java 8 and older (faster than instantiation of new Throwable, but depends on the target JVM)

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

17 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Callers

Java Maven Central License: MIT

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.

Installation

Maven

<dependency>
    <groupId>com.ydo4ki</groupId>
    <artifactId>Callers</artifactId>
    <version>1.3</version>
</dependency>

Gradle

implementation("com.ydo4ki:Callers:1.3")

No build system

Go to the releases tab and download latest jar

How to build

Please note that you are required to have JDKs 1.4, 1.8 and 9+ on your computer to compile this.

  1. Clone this repository
git clone https://github.com/Y-Sulphuris/Callers.git
cd Callers
  1. 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
  1. Run maven build (maven should run on Java 9 or higher):
mvn clean package

As for where to get JDK 1.4, I'll tactfully refrain from commenting on this.

About

Small library that gives you access to getCallerClass() for Java 8 and older (faster than instantiation of new Throwable, but depends on the target JVM)

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages