如何在 java 中调用 super 之前 运行 一个函数?

How to run a function before calling super in java?

我有一个获取 HashSet 和 HashMap 的构造函数。我需要 运行 对一个 hashMAp 进行验证检查并将其与 hashSet 组合,因为 'super' 必须只接收一个 hashSet。 我找不到解决方法,因为出现以下错误:cannot reference this before supertype constructor

示例:

public class A extends B {
  public A(HashSet<Obj> h1, HashMap<UID,Objects> m1) {
    super(new C (h1) ); //h1 should contain changes related to m1..
}

我想做这样的事情:

public class A extends B {
      public A(HashSet<Obj> h1, HashMap<UID,Objects> m1) {
        runMyFunc(h1,m1);
        super(new C (h1) );
    }



 runMyFunc(HashSet<Obj> h1, HashMap<UID,Objects> m1){
      //do checks
      //more checks...
      // if something then h1.setUid(m1.get(0))... 
      return h1;
   }

我想将构造函数转换为私有的,然后 运行 就这样:

public class A extends B {
  private A(HashSet<Obj> h1) {
    super(new C (h1) ); 
}

 public A(HashSet<Obj> h1, HashMap<UID,Objects> m1) {
     runMyFunc(h1,m1);
     this(h1);
 }

但它也没有用。

能请教一下吗?

制作您的方法 static 并确保它 returns 您的新方法 h1

public static HashSet<Obj> runMyFunc(HashSet<Obj> h1, HashMap<UID,Objects> m1) {
     // Some mutation to h1
     return h1;
}

在第一行使用如下:

this(runMyFunc(h1,m1));

但是为什么呢?

你一定想知道 "Why am I able to use static methods and not instance methods?"。那么,在调用方法之前,必须先实例化父对象的对象,这是为了帮助编译器防止您访问尚不可用的 attributes/methods/whatever。静态方法是安全的,因为根据定义它不能访问其中任何一个。

相关帖子

  • Why does this() and super() have to be the first statement in a constructor?

  • Constructor call must be the first statement in a constructor

只需让您的 runMyFunc 静态 ,并将其作为函数调用,您在 super 调用中使用 return 值。这是允许的:

public class A extends B {
  public A(HashSet<Obj> h1, HashMap<UID,Objects> m1) {
     // Invoke as function rather than by itself on a separate line
     super(new C (runMyFunc(h1,m1)) );
  }

  // Make method static
  public static HashSet<Obj> runMyFunc(HashSet<Obj> h1, HashMap<UID,Objects> m1) {
     //do checks
     //more checks...
     // if something then h1.setUid(m1.get(0))... 
     return h1;
  }