www1350 / javaweb

http://www1350.github.io/
31 stars 5 forks source link

反射实现回调 #95

Open www1350 opened 7 years ago

www1350 commented 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);
    }
}