静态(static)方法没有this指针,我觉得只能hard code

解决方案 »

  1.   

    完全可以达到你的目标,只不过要用非常规的方法
    代码如下
    class B
    {
        public static void TT()
        {
            try{
                throw  new Exception();
            }
            catch(Exception e){
                StackTraceElement[] elems=e.getStackTrace();
               int deeps=elems.length;
               if(deeps<2) {
                    System.out.println("illegal!");
                }
                else{
                    System.out.println("this  static method of class "+
                                    elems[0].getClassName()+" is invoked by class "+
                                    elems[1].getClassName());
                }
            }
         }
    }
    class A{    
        public static void main(String args[])
        {
            B.TT();
        }
    }
    你看看结果!!
      

  2.   

    很新奇的解法。
    但好象编译不过,StackTraceElement是哪个包里的类,可否解释一下?
      

  3.   

    我执行了一下报以下的错误:
    Exception in thread "main" java.lang.NoSuchMethodError
            at B.TT(A.java:9)
            at A.main(A.java:25)我在api理查了一下确有此类,由此方法,可为什么会有这样的错误呢?
    可否解释一下
      

  4.   

    xyzxyz1111的解法很新奇,但要在程序正常结束的情况下不能解决,有没有更好的办法?
      

  5.   

    我的建议是修改设计,避免这样的情况出现,如可以对这个方法增加一个参数static void TT(Class c) {}
      

  6.   

    上面那个例子太麻烦了,也很怪
    你的意思是不是这样?
    仅仅是通过静态方法得到该类的名字?class Test
    {
    public static String getName ()
    {
    return Test.class.getName();
    }

    public static void main (String[] args)
    {
    System.out.println("The name of class is: " + Test.getName());
    }
    }
      

  7.   

    可能我理解错了,我认为楼主的意思不是获得静态方法所在的类名,而是获得调用这个方法的方法(在我的例中是main)所在的类名(这里是A)。不过一样可以得到静态方法本身的类名,而不用如上面的例子的所谓的硬编码!
      

  8.   

    xyzxyz1111(小淫贼)最后的理解对了,呵呵,文字表达不够清晰,谁还有更好的办法?
    有了马上结贴
      

  9.   

    xyzxyz1111(小淫贼)的TT用的好!!!!
      

  10.   

    应该没有办法。The only way is to pass the Class as the parameter.public static void methodNeedCallerClass(Class cls)
    {
      ......
    }///////////////////////////////////////////////////
    //not static method.
    {
       ...
       methodNeedCallerClass(this.getClass());
       ...
    }
    //static method in Class Caller.
    {
       ...
       methodNeedCallerClass(Caller.class);
       ...
    }