class A {
public static void log() {
System.out.println(是谁调用了我?);
}
}
class B {
public static void main(String[] args) {
A.log();
}
}
输出结果:classname=A methodname=main
...全文
1577打赏收藏
如何得到调用这个方法的类的class name 和method name?
class A { public static void log() { System.out.println(是谁调用了我?); } } class B { public static void main(String[] args) { A.log(); } } 输出结果:classname=A methodname=main
/*
* Created on Dec 15, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.didoleo.demo;
/**
* @author dido leo
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class ProxyClass implements InvocationHandler{
Object obj;
public ProxyClass(Object o){
obj=o;
}
public String getInvokeClassName(){
return ((A)obj).getInvokeClassName();
}
/*
* Created on Dec 15, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.didoleo.demo;
/**
* @author dido leo
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public interface MyInterface {
void method();
}
/*
* Created on Dec 15, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.didoleo.demo;
/**
* @author dido leo
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class A implements MyInterface{
Object o=null;
public A(Object o){
this.o=o;
}
public String getInvokeClassName(){
return o.getClass().getName();
}
public void method(){
System.out.println("do something...");
}
}
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.didoleo.demo;
import java.lang.reflect.Proxy;
/**
* @author dido leo
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class B {
public static void main(String[] args){
MyInterface myintf=(MyInterface)Proxy.newProxyInstance(
MyInterface.class.getClassLoader(),
new Class[]{MyInterface.class},
new ProxyClass(new A(new B()))
);
myintf.method();
}
}