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

use*_*966 5 java inheritance super

我有一个构造函数,它获取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..
}
Run Code Online (Sandbox Code Playgroud)

我想做那样的事情:

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;
   }
Run Code Online (Sandbox Code Playgroud)

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

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);
 }
Run Code Online (Sandbox Code Playgroud)

但它也没有用.

你能建议吗?

Erw*_*idt 6

只需创建runMyFunc 静态,并将其作为函数调用,您可以在super调用中使用返回值.这是允许的:

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;
  }
Run Code Online (Sandbox Code Playgroud)


Ani*_*oin 5

制定方法 static并确保它返回新的方法h1.

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

在第一行中使用它如下:

this(runMyFunc(h1,m1));
Run Code Online (Sandbox Code Playgroud)

为什么我能够使用静态方法而不是实例方法?

在调用方法之前,首先要实例化父对象,以便编译器阻止您访问属性/方法/任何尚未可用的属性/方法.静态方法是安全的,因为定义无法访问其中任何一个.

相关问题

为什么this()和super()必须是构造函数中的第一个语句?

构造函数调用必须是构造函数中的第一个语句

  • @StephenC正在讨论meta - > http://meta.stackoverflow.com/questions/342484/should-you-refrain-from-answering-if-you-cant-format-an-answer?cb=1 (2认同)