-1

我有以下代码。

家长班:

class Parent{

        void a()
        {   
             if(// some logic to check whether child class is calling this method or some other class//)
             System.out.println("Child class is calling..")}
        }

儿童班:

class Child extends Parent{

        void b(){System.out.println(new Parent().a());}
}

其他一些类:

 class Child1{

        void b(){System.out.println(new Parent().a());}
}

在这里,我从一个子类和另一个类调用父母 a() 方法。

我的问题是我应该在 Parent 的方法的 if 块中放入什么逻辑,以便我可以确定哪个类正在调用这个方法。

我有一些代码,但它不起作用。请帮我看看这段代码有什么问题。

if(this.getClass().getClassLoader()
            .loadClass(new Throwable().getStackTrace()[0].getClassName())
            .newInstance() instanceof Parent)
 {
           System.out.println("Child class is calling..")}
 }
4

2 回答 2

1

您有以下选择:

  1. 移动Parent到不同的包并使其a()受到保护。由于新包中没有其他类,因此只有子类能够调用该方法。

  2. 您可以尝试堆栈跟踪方法,但您寻找的信息不在第一帧 - 第一帧是您调用的位置new Throwable()。尝试使用第 1 帧(这就是调用的地方a()):

    ...getStackTrace()[1]...
    

    如果你关心性能,你应该缓存这个结果。

也就是说,我想知道这段代码的目的是什么。我的直觉是,您通过创建一个会引起不同痛苦的脆弱工作来解决更深层次的问题。也许您应该告诉我们您想要实现的目标(大局)。

于 2012-05-28T14:18:46.427 回答
1

我想出了这样的东西,也许这就是你在找什么

package pack;

class Parent {

    void a() {
        //my test
        try{
            throw new Exception();
        }
        catch (Exception e){
            //e.printStackTrace();
            if (!e.getStackTrace()[1].getClassName().equals("pack.Parent"))
                throw new RuntimeException("method can be invoked only in Parrent class");
        }

        //rest of methods body
        System.out.println("hello world");

    }

    public void b(){
        a();
    }

    //works here
    public static void main(String[] args) {
        new Parent().a();
        new Parent().b();
    }
}
class Child extends Parent{
    //RuntimeException here
    public static void main(String[] args) {
        new Parent().a();
        new Parent().b();
    }
}
class Child2{
    //RuntimeException here
    public static void main(String[] args) {
        new Parent().a();
        new Parent().b();
    }
}

忘了提到该b方法在所有类中都可以正常工作。希望这就是你想要的。顺便说一句,如果你不想要 RuntimeException 然后尝试return或抛出其他异常。

于 2012-05-28T15:11:38.397 回答