Java 如何使用stacktrace或reflection查找方法的调用方?
我需要找到方法的调用方。可以使用stacktrace或reflection吗?我以前做过。您只需创建一个新的异常并获取其上的堆栈跟踪,而无需抛出它,然后检查堆栈跟踪。但是,正如另一个答案所说,这是非常昂贵的——不要在一个紧密的循环中进行 我以前在一个性能无关紧要的应用程序上为日志记录实用程序做过这项工作(事实上,性能根本不重要——只要你将结果显示在一个动作上,比如快速点击按钮) 在获取堆栈跟踪之前,异常只有.printStackTrace(),因此我必须将System.out重定向到我自己创建的流,然后(新异常()).printStackTrace();将System.out重定向回并分析流。有趣的东西Java 如何使用stacktrace或reflection查找方法的调用方?,java,stack-trace,Java,Stack Trace,我需要找到方法的调用方。可以使用stacktrace或reflection吗?我以前做过。您只需创建一个新的异常并获取其上的堆栈跟踪,而无需抛出它,然后检查堆栈跟踪。但是,正如另一个答案所说,这是非常昂贵的——不要在一个紧密的循环中进行 我以前在一个性能无关紧要的应用程序上为日志记录实用程序做过这项工作(事实上,性能根本不重要——只要你将结果显示在一个动作上,比如快速点击按钮) 在获取堆栈跟踪之前,异常只有.printStackTrace(),因此我必须将System.out重定向到我自己创建的
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
根据Javadocs:
数组的最后一个元素表示堆栈的底部,它是序列中最近的方法调用
StackTraceElement
具有getClassName()
、getFileName()
、getLineNumber()
和getMethodName()
你必须通过实验来确定你想要的索引
(可能是
stackTraceElements[1]
或[2]
)。听起来像是在试图避免将对此
的引用传递到方法中。传递此
比通过当前堆栈跟踪查找调用方要好得多重构到更面向对象的设计甚至更好。您不需要知道调用方。如有必要,传递回调对象。/**
/**
* Get the method name for a depth in call stack. <br />
* Utility function
* @param depth depth in the call stack (0 means current method, 1 means call method, ...)
* @return method name
*/
public static String getMethodName(final int depth)
{
final StackTraceElement[] ste = new Throwable().getStackTrace();
//System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName());
return ste[ste.length - depth].getMethodName();
}
*获取调用堆栈中深度的方法名称
*效用函数
*@param depth调用堆栈中的深度(0表示当前方法,1表示调用方法,…)
*@return方法名
*/
公共静态字符串getMethodName(最终整数深度)
{
最终StackTraceElement[]ste=新的可丢弃项().getStackTrace();
//System.out.println(ste[ste.length-depth].getClassName()+“#”+ste[ste.length-depth].getMethodName());
返回ste[ste.length-depth].getMethodName();
}
例如,如果您试图获取用于调试的调用方法行,则需要通过编写这些静态方法的实用程序类:
(旧的java1.4代码,仅用于说明StackTraceElement的潜在用法)
/**
*返回第一个类的第一个“[class#method(line)]:”不等于“StackTraceUtils”
*从堆栈跟踪。
*@return“[class#method(line)]:”(永远不要为空,第一类超过StackTraceUtils)
*/
公共静态字符串getClassMethodLine()
{
返回getClassMethodLine(null);
}
/**
*返回第一个类的第一个“[class#method(line)]:”不等于“StackTraceUtils”和aclass
*允许通过某个类。
*@param aclass类在堆栈跟踪中获得通过。如果为空,则仅尝试通过StackTraceUtils。
*@return“[class#method(line)]:”(永远不要为空,因为如果找不到aclass,则返回超过StackTraceUtils的第一个类)
*/
公共静态字符串getClassMethodLine(最终类aclass)
{
最终StackTraceeElement st=GetCallingStackTraceeElement(aclass);
最后一个字符串amsg=“[”+st.getClassName()+“#”+st.getMethodName()+”(“+st.getLineNumber())
+")] : ";
返回amsg;
}
/**
*返回第一个类的第一个堆栈跟踪元素,该元素不等于“StackTraceUtils”或“LogUtils”和aClass
*存储在调用堆栈的数组中
*允许通过某个类。
*@param aclass类在堆栈跟踪中获得通过。如果为空,则仅尝试通过StackTraceUtils。
*@return stackTraceeElement(从不为null,因为如果找不到aClass,则返回超过StackTraceUtils的第一个类)
*@如果生成的statckTrace为null,则抛出断言FailedException(RuntimeException)
*/
公共静态StackTraceElement getCallingStackTraceElement(最终类aclass)
{
最终可丢弃t=新可丢弃();
最终StackTraceElement[]ste=t.getStackTrace();
int指数=1;
最终int限值=钢长度;
StackTraceElement st=ste[索引];
字符串className=st.getClassName();
布尔值aclassfound=false;
if(aclass==null)
{
aclassfound=true;
}
StackTraceeElement resst=null;
while(指数<极限)
{
if(shouldesamine(className,aclass)==true)
{
if(resst==null)
{
resst=st;
}
if(aclassfound==true)
{
最终StackTraceElement ast=onClassfound(aclass、className、st);
如果(ast!=null)
{
resst=ast;
打破
}
}
其他的
{
if(aclass!=null&&aclass.getName().equals(className)==true)
{
aclassfound=true;
}
}
}
指数=指数+1;
st=st[指数];
className=st.getClassName();
}
if(resst==null)
{
//Assert.isNotNull(resst,“堆栈跟踪应为null”);//没有其他循环依赖项
抛出新断言FailedException(StackTraceUtils.getClassMethodLine()+“null参数:”+“堆栈跟踪应为null”);//$NON-NLS-1$
}
返回resst;
}
静止的
/**
* Returns the first "[class#method(line)]: " of the first class not equal to "StackTraceUtils". <br />
* From the Stack Trace.
* @return "[class#method(line)]: " (never empty, first class past StackTraceUtils)
*/
public static String getClassMethodLine()
{
return getClassMethodLine(null);
}
/**
* Returns the first "[class#method(line)]: " of the first class not equal to "StackTraceUtils" and aclass. <br />
* Allows to get past a certain class.
* @param aclass class to get pass in the stack trace. If null, only try to get past StackTraceUtils.
* @return "[class#method(line)]: " (never empty, because if aclass is not found, returns first class past StackTraceUtils)
*/
public static String getClassMethodLine(final Class aclass)
{
final StackTraceElement st = getCallingStackTraceElement(aclass);
final String amsg = "[" + st.getClassName() + "#" + st.getMethodName() + "(" + st.getLineNumber()
+")] <" + Thread.currentThread().getName() + ">: ";
return amsg;
}
/**
* Returns the first stack trace element of the first class not equal to "StackTraceUtils" or "LogUtils" and aClass. <br />
* Stored in array of the callstack. <br />
* Allows to get past a certain class.
* @param aclass class to get pass in the stack trace. If null, only try to get past StackTraceUtils.
* @return stackTraceElement (never null, because if aClass is not found, returns first class past StackTraceUtils)
* @throws AssertionFailedException if resulting statckTrace is null (RuntimeException)
*/
public static StackTraceElement getCallingStackTraceElement(final Class aclass)
{
final Throwable t = new Throwable();
final StackTraceElement[] ste = t.getStackTrace();
int index = 1;
final int limit = ste.length;
StackTraceElement st = ste[index];
String className = st.getClassName();
boolean aclassfound = false;
if(aclass == null)
{
aclassfound = true;
}
StackTraceElement resst = null;
while(index < limit)
{
if(shouldExamine(className, aclass) == true)
{
if(resst == null)
{
resst = st;
}
if(aclassfound == true)
{
final StackTraceElement ast = onClassfound(aclass, className, st);
if(ast != null)
{
resst = ast;
break;
}
}
else
{
if(aclass != null && aclass.getName().equals(className) == true)
{
aclassfound = true;
}
}
}
index = index + 1;
st = ste[index];
className = st.getClassName();
}
if(resst == null)
{
//Assert.isNotNull(resst, "stack trace should null"); //NO OTHERWISE circular dependencies
throw new AssertionFailedException(StackTraceUtils.getClassMethodLine() + " null argument:" + "stack trace should null"); //$NON-NLS-1$
}
return resst;
}
static private boolean shouldExamine(String className, Class aclass)
{
final boolean res = StackTraceUtils.class.getName().equals(className) == false && (className.endsWith("LogUtils"
) == false || (aclass !=null && aclass.getName().endsWith("LogUtils")));
return res;
}
static private StackTraceElement onClassfound(Class aclass, String className, StackTraceElement st)
{
StackTraceElement resst = null;
if(aclass != null && aclass.getName().equals(className) == false)
{
resst = st;
}
if(aclass == null)
{
resst = st;
}
return resst;
}
sun.reflect.Reflection
/** Returns the class of the method <code>realFramesToSkip</code>
frames up the stack (zero-based), ignoring frames associated
with java.lang.reflect.Method.invoke() and its implementation.
The first frame is that associated with this method, so
<code>getCallerClass(0)</code> returns the Class object for
sun.reflect.Reflection. Frames associated with
java.lang.reflect.Method.invoke() and its implementation are
completely ignored and do not count toward the number of "real"
frames skipped. */
public static native Class getCallerClass(int realFramesToSkip);
/**
* Test the speed of various methods for getting the caller class name
*/
public class TestGetCallerClassName {
/**
* Abstract class for testing different methods of getting the caller class name
*/
private static abstract class GetCallerClassNameMethod {
public abstract String getCallerClassName(int callStackDepth);
public abstract String getMethodName();
}
/**
* Uses the internal Reflection class
*/
private static class ReflectionMethod extends GetCallerClassNameMethod {
public String getCallerClassName(int callStackDepth) {
return sun.reflect.Reflection.getCallerClass(callStackDepth).getName();
}
public String getMethodName() {
return "Reflection";
}
}
/**
* Get a stack trace from the current thread
*/
private static class ThreadStackTraceMethod extends GetCallerClassNameMethod {
public String getCallerClassName(int callStackDepth) {
return Thread.currentThread().getStackTrace()[callStackDepth].getClassName();
}
public String getMethodName() {
return "Current Thread StackTrace";
}
}
/**
* Get a stack trace from a new Throwable
*/
private static class ThrowableStackTraceMethod extends GetCallerClassNameMethod {
public String getCallerClassName(int callStackDepth) {
return new Throwable().getStackTrace()[callStackDepth].getClassName();
}
public String getMethodName() {
return "Throwable StackTrace";
}
}
/**
* Use the SecurityManager.getClassContext()
*/
private static class SecurityManagerMethod extends GetCallerClassNameMethod {
public String getCallerClassName(int callStackDepth) {
return mySecurityManager.getCallerClassName(callStackDepth);
}
public String getMethodName() {
return "SecurityManager";
}
/**
* A custom security manager that exposes the getClassContext() information
*/
static class MySecurityManager extends SecurityManager {
public String getCallerClassName(int callStackDepth) {
return getClassContext()[callStackDepth].getName();
}
}
private final static MySecurityManager mySecurityManager =
new MySecurityManager();
}
/**
* Test all four methods
*/
public static void main(String[] args) {
testMethod(new ReflectionMethod());
testMethod(new ThreadStackTraceMethod());
testMethod(new ThrowableStackTraceMethod());
testMethod(new SecurityManagerMethod());
}
private static void testMethod(GetCallerClassNameMethod method) {
long startTime = System.nanoTime();
String className = null;
for (int i = 0; i < 1000000; i++) {
className = method.getCallerClassName(2);
}
printElapsedTime(method.getMethodName(), startTime);
}
private static void printElapsedTime(String title, long startTime) {
System.out.println(title + ": " + ((double)(System.nanoTime() - startTime))/1000000 + " ms.");
}
}
Reflection: 10.195 ms.
Current Thread StackTrace: 5886.964 ms.
Throwable StackTrace: 4700.073 ms.
SecurityManager: 1046.804 ms.
> java -version
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
> java TestGetCallerClassName
Reflection: 0.194s.
Current Thread StackTrace: 3.887s.
Throwable StackTrace: 3.173s.
SecurityManager: 0.565s.
public class InstanceCount{
private static Map<Integer, CounterInstanceLog> instanceMap = new HashMap<Integer, CounterInstanceLog>();
private CounterInstanceLog counterInstanceLog;
public void count() {
counterInstanceLog= new counterInstanceLog();
if(counterInstanceLog.getIdHashCode() != 0){
try {
if (instanceMap .containsKey(counterInstanceLog.getIdHashCode())) {
counterInstanceLog= instanceMap .get(counterInstanceLog.getIdHashCode());
}
counterInstanceLog.incrementCounter();
instanceMap .put(counterInstanceLog.getIdHashCode(), counterInstanceLog);
}
(...)
}
public class CounterInstanceLog{
private int idHashCode;
private StackTraceElement[] arrayStackTraceElements;
private int instanceCount;
private String callerClassName;
private StackTraceElement getProjectClasses(int depth) {
if(depth< 10){
getCallerClassName(sun.reflect.Reflection.getCallerClass(depth).getName());
if(getCallerClassName().startsWith("com.yourproject.model")){
setStackTraceElements(Thread.currentThread().getStackTrace());
setIdHashCode();
return arrayStackTraceElements[depth];
}
//+2 because one new item are added to the stackflow
return getProjectClasses(profundidade+2);
}else{
return null;
}
}
private void setIdHashCode() {
if(getNomeClasse() != null){
this.idHashCode = (getCallerClassName()).hashCode();
}
}
public void incrementaContador() {
this.instanceCount++;
}
//getters and setters
(...)
}
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
class DBConnection {
String createdBy = null;
DBConnection(Throwable whoCreatedMe) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(os);
whoCreatedMe.printStackTrace(pw);
try {
createdBy = os.toString();
pw.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ThrowableTest {
public static void main(String[] args) {
Throwable createdBy = new Throwable(
"Connection created from DBConnectionManager");
DBConnection conn = new DBConnection(createdBy);
System.out.println(conn.createdBy);
}
}
public static interface ICallback<T> { T doOperation(); }
public class TestCallerOfMethod {
public static <T> T callTwo(final ICallback<T> c){
// Pass the object created at callee to the caller
// From the passed object we can get; what is the callee name like below.
System.out.println(c.getClass().getEnclosingMethod().getName());
return c.doOperation();
}
public static boolean callOne(){
ICallback callBackInstance = new ICallback(Boolean){
@Override
public Boolean doOperation()
{
return true;
}
};
return callTwo(callBackInstance);
}
public static void main(String[] args) {
callOne();
}
}
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
stackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
System.out.println(e.getMethodName());
public class TestString {
public static void main(String[] args) {
TestString testString = new TestString();
testString.doit1();
testString.doit2();
testString.doit3();
testString.doit4();
}
public void doit() {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
System.out.println(e.getMethodName());
}
public void doit1() {
doit();
}
public void doit2() {
doit();
}
public void doit3() {
doit();
}
public void doit4() {
doit();
}
}
private void parseExceptionContents(
final Exception exception,
final OutputStream out)
{
final StackTraceElement[] stackTrace = exception.getStackTrace();
int index = 0;
for (StackTraceElement element : stackTrace)
{
final String exceptionMsg =
"Exception thrown from " + element.getMethodName()
+ " in class " + element.getClassName() + " [on line number "
+ element.getLineNumber() + " of file " + element.getFileName() + "]";
try
{
out.write((headerLine + newLine).getBytes());
out.write((headerTitlePortion + index++ + newLine).getBytes() );
out.write((headerLine + newLine).getBytes());
out.write((exceptionMsg + newLine + newLine).getBytes());
out.write(
("Exception.toString: " + element.toString() + newLine).getBytes());
}
catch (IOException ioEx)
{
System.err.println(
"IOException encountered while trying to write "
+ "StackTraceElement data to provided OutputStream.\n"
+ ioEx.getMessage() );
}
}
}
Thread.currentThread().getStackTrace()[2].getMethodName()
StackWalker walker = StackWalker
.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
Class<?> callerClass = walker.getCallerClass();
walker.walk(frames -> frames
.map(StackWalker.StackFrame::getDeclaringClass)
.skip(1)
.findFirst());