Skip to content

Instantly share code, notes, and snippets.

@kares
Created July 15, 2013 07:49
Show Gist options
  • Select an option

  • Save kares/5998167 to your computer and use it in GitHub Desktop.

Select an option

Save kares/5998167 to your computer and use it in GitHub Desktop.
return the caller's method
/**
* inspired by JavaCPP's Loader utility
* @see http://bit.ly/loader-java
*/
public class Caller {
/**
* Returns the {@link Class} object that contains a caller's method.
*
* @param i the offset on the call stack of the method of interest
* @return the Class found from the calling context, or {@code null} if not found
*/
public static Class getCallerClass(int i) {
Class[] classContext = new SecurityManager() {
@Override public Class[] getClassContext() {
return super.getClassContext();
}
}.getClassContext();
if (classContext != null) {
for (int j = 0; j < classContext.length; j++) {
if (classContext[j] == Loader.class) {
return classContext[i+j];
}
}
} else {
// SecurityManager.getClassContext() returns null on Android 4.0
try {
StackTraceElement[] classNames = Thread.currentThread().getStackTrace();
for (int j = 0; j < classNames.length; j++) {
if (Class.forName(classNames[j].getClassName()) == Loader.class) {
return Class.forName(classNames[i+j].getClassName());
}
}
} catch (ClassNotFoundException e) { }
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment