Open www1350 opened 7 years ago
public class ClassA { public void method1(){ System.out.println("hello method1"); } public static void main(String[] args){ ClassB classB = new ClassB(); classB.callback("method1"); } }
public class ClassB { @SuppressWarnings({ "rawtypes", "unchecked" }) public void callback(String methodName){ String className = ""; StackTraceElement[] traces = Thread.currentThread().getStackTrace(); for(StackTraceElement trace : traces){ String thisTrace = this.getClass().getName()+".callback"; if(trace.toString().equals(thisTrace)){ break; } className = trace.getClassName(); } try { Class clazz = Class.forName(className); Method method = clazz.getMethod(methodName, new Class[0]); Object obj = clazz.newInstance(); method.invoke(obj, new Object[0]); } catch (Exception e) { e.printStackTrace(); } System.out.println(className); } }