Home > Mobile >  Javac make compiler fail on attribute getter calling itself
Javac make compiler fail on attribute getter calling itself

Time:10-25

I'm using javac (--version : javac 17.0.4.1 to compile my files at the moment but I am having an issue. I have a bad habit of abusing autocomplete a bit and sometimes it isn't smart. One example is when defining a getter for an attribute, I would write

public T getAttrib(){
    return this.getAttrib();
}

instead of

public T getAttrib(){
    return this.attrib;
}

which as you can imagine can be problematic. My true issue, is that javac doesn't catch that, and I have to wait for runtime errors. Or at least doesn't give a warning. Now I understand why that is, there might be cases where it is entirely legitimate to do something similar with some checks... maybe...

But is there a compiler option I can enable to check for that? I tried -Xlint:all but it didn't catch it. I've read the man page of javac, but couldn't find anything that would allow me to do that.

I'm coming from C so I am used to my compiler warning me about most dodgy things, and most easy to do errors are caught before runtime... well some are not, but with proper compiler arguments, one can mitigate them by a lot.

Is there something similar in javac that would allow me to catch this mistake?

Thanks for any input on this.

(also yes I could disable autocomplete, I've lived without while coding for a while, and a crappy autocomplete is worse than no autocomplete... but hey, you don't fix plumbing by not using the toilets)

CodePudding user response:

This isn't a compiler error or warning, because in general the compiler only fails when the code is invalid according to the Java Language Specification, and warnings are only generally emitted for things like unsafe casts which could cause heap corruption, not all probable mistakes.

However, other tools such as IDEs and linters can warn about probable mistakes. For example, IntelliJ IDEA has an inspection for "infinite recursion", which should generate a warning for this code.

CodePudding user response:

But is there a compiler option I can enable to check for that?

No there isn't. A getter calling itself will produce and endless loop at runtime, so it's a programming error. Programatically is doable, if fore some reason you want to, like if you make a loop that never satisfy the exit condition.

In short, you have to fix it yourself

  • Related