This post was brought to you by this PMD rule.
Transcription
Why do we have this stupid code analyzer rule enabled anyway? Nobody writes code like this…
After telling them the lore why it’s there:
You have seen such things before?
11 Times, as a matter of fact
the 2nd does that already
in the first you can’t, as
getClass()
is not a static method (wouldn’t even make sense if it was)The GP is saying that
String
is a class already, you shouldn’t have to callString.class
.Personally, I’m away from it for long enough that I don’t remember either.
I don’t believe there is much deeper of an explanation than “because the Java designers didn’t implement support for that”.
That feature is called “types as a first-class value” and you need to implement some special casing or an entire system in the language to make it work. Telling devs there’s a special static variable
.class
is conceptually simpler to implement and understand.Is it simpler tho? You have to explain to someone that the Type is also an Object with the field .class on it. I feel like just saying it’s a Type and you can reference Types directly is simpler. Idk maybe I’ve been currupted by type theory too much lol
Well, I think your idea would be simpler, if we weren’t talking about Java.
Pretty much everything is an object in Java. It’s only logical that a type would also be an object and have associated fields.
Similarly, what you’re thinking of as “reference types directly” doesn’t make sense in Java, because it lacks many of the systems to make that actually usable like a type. What you get from
.class
is aClass
object, which you can’t stick into a generic type parameter, for example.It basically uses reflection to give you e.g. the name of that type and you can also instantiate an object of that type, if no parameters need to be passed to the constructor function.
And then, yeah, I think for explaining that you merely get an object which roughly describes the type, the separate
.class
field is a good idea.