-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());}
}

ここでは、1 つの子クラスと別のクラスから Parents a() メソッドを呼び出しています。

私の質問は、どのクラスがこのメソッドを呼び出しているかを判断できるように、親のメソッドの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 に答える