How to run a function before calling super in java?

I have a constructor that gets HashSet and HashMap. I need to run a validation check on one hashMAp and combine it with a hashSet, since "super" should only get one hashSet. I cannot find a way to do this, as I get the following error: cannot reference this before supertype constructor

Example:

 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.. } 

I want to do something like this:

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

I thought the conversion of the constructor to private, and then run it like this:

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

but it also did not work.

Can you consult?

+5
source share
2 answers

Make your method static and make sure it returns the new h1 .

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

Use it on the first line as follows:

 this(runMyFunc(h1,m1)); 

Why can I use static methods and not instance methods?

Before you can call your methods, your parent must be created so that the compiler cannot access attributes / methods / topics that are not yet available. Static methods are safe by definition, cannot access such one of them.

Related Questions

Why should this () and super () be the first statement in the constructor?

The constructor request must be the first statement in the constructor

+5
source

Just create runMyFunc static and call it as a function in which you use the return value in a super call. It is allowed:

 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; } 
+6
source

Source: https://habr.com/ru/post/1263538/


All Articles