【问题标题】:Can a parent method check which child method calls it? [duplicate]父方法可以检查哪个子方法调用它吗? [复制]
【发布时间】:2017-05-09 12:56:15
【问题描述】:

我是 Java 的新手,我正在编写一个程序,它有两个使用相同父方法的子类,我想找到一种方法来跟踪哪个调用了该方法。

例子:

public class Parent(){
    public static int ChildOneUses, ChildTwoUses;
    public void Example(){
        /* code */
        if(/*ChildOne called the method*/)
            ChildOneUses++;
        else if(/*ChildTwo called the method*/)
            ChildTwoUses++;
    }
}

public class ChildOne extends Parent(){
    /* code */
}
public class ChildTwo extends Parent(){
    /* code */
}

public static void main(String[] args){
    ChildOne ChildOne = new ChildOne();
    ChildTwo ChildTwo = new ChildTwo();

    ChildOne.Example();

    ChildTwo.Example();
    ChildTwo.Example();
}

/* If this code were to run, ChildOneUses would equal 1 and ChildTwoUses would equal 2 */

我不确定这个问题是否有答案,而不仅仅是将父方法移动到每个子类以自行跟踪它们。

【问题讨论】:

  • 即使有办法做到这一点,这几乎肯定是糟糕的 oop 风格。
  • 为什么你想像这样跟踪方法调用?目的是什么?
  • 我仍在学习 java 的过程中,我喜欢编写随机程序来帮助我学习并将这些新想法巩固在我的记忆中,有时它们会让我处于我想要的位置需要学习新事物(像这样),然后我试图找到答案

标签: java class methods parent-child


【解决方案1】:

您可以在父类中设置 childType。

public class Parent(){
   public static int childOneUses, childTwoUses;
   public static int childType;

   public Parent(int childType) {
      this.childType = childType;
   }

   public void example(){
    if(childType == 1) {
        childOneUses++;
    }
    else if(childType == 2) {
        childTwoUses++;
    }
   }
}

public class ChildOne extends Parent(){
  public ChildOne() {
    super(1);
  }
}

public class ChildTwo extends Parent(){
  public ChildTwo() {
    super(2);
  }
}

public static void main(String[] args){
ChildOne childOne = new ChildOne();
ChildTwo childTwo = new ChildTwo();

childOne.example();

childTwo.example();
childTwo.example();
}

【讨论】:

  • 谢谢,真的很有帮助!我仍然掌握了父子类的窍门,这是一个很酷的技巧,知道它可以应用于其他事情!
【解决方案2】:

你可以在子类中创建一个显示类名的方法,或者你可以在父类中创建这个方法,让其他孩子现在每次都获得这个方法你想跟踪你让对象调用这个方法 nameOfObject.getClass().getName()

例如,如果你把字符串 s 写成 s.getClass().getName() 输出是 java.lang.String 现在你可以使用这个输出,如果你想要的话,只取最后一个词并且你得到了类名

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多