日期:2014-05-20 浏览次数:20915 次
//filename is:FindTheClassOfTheMethodCall.java
//
package csdn.oop;
class ObjectTest
{
public ObjectTest(){}
public void whoCalledMe()
{
//--------------------------------------------就这部分
String clazzName = new SecurityManager()
{
public String getClassName()
{
return getClassContext()[2].getName();//0 是 这个内部类,1 是ObjectTest,2是外部直接调用类,3 是更上一级。
}
}.getClassName();
System.out.println("Current class that invoking this method is: "+clazzName);
}
}
class ClassOne
{
public static void main(String args[])
{
ObjectTest obj = new ObjectTest();
obj.whoCalledMe();
}
}
class ClassTwo
{
public static void main(String args[])
{
ObjectTest obj = new ObjectTest();
obj.whoCalledMe();
}
}
class ClassThree
{
public static void main(String args[])
{
ObjectTest obj = new ObjectTest();
obj.whoCalledMe();
}
}
class FindTheClassOfTheMethodCall
{
public static void main(String[] args)
{
ClassOne.main(args);
ClassTwo.main(args);
ClassThree.main(args);
}
}
Thread.currentThread().getStackTrace()[2].getClassName()
Thread.currentThread().getStackTrace()[1].getMethodName();