开发者

How to get class name from a static method using reflection

i'm looking for a way of getting the class name of the class a static method is invoked on.

eg:

public  class MySuperClass{
    public static String getClassName(){
        //some trick here...
    }
}

and

public  class MyInheritingClass extends开发者_如何学编程 MySuperClass{
        //some interesting code here...
        public static void main(String [ ] args){
            System.out.println(MyInheritingClass.getClassName());
            //this should output "MyInheritingClass" and NOT "MySuperClass"
        }
    }

Any idea of how to work it out? thanks


public  class MyInheritingClass extends MySuperClass{
    //some interesting code here...
    public static void main(String [ ] args){
        System.out.println(MyInheritingClass.getClassName());
        //this should output "MyInheritingClass" and NOT "MySuperClass"
    }
}

This a very misleading way of invoking a static method. It should be illegal. Static methods are not virtual. There is absolutely no possible way to do what you're trying to do.


this should output "MyInheritingClass" and NOT "MySuperClass"

Then why not just:

MyInheritingClass.class.getSimpleName()

?


Try this:

public  class MySuperClass{
    public  String getClassName(){
        return getClass().getName();
    }
}


public  class MyInheritingClass extends MySuperClass{
    public static void main(String [ ] args){
        System.out.println(new MyInheritingClass().getClassName());
    }
}


try this

this.getClass().getCanonicalName()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜