Why do you have to use .class
in Java to get the Class
object? Why not just the class name like in Ruby?
I know Ruby
and Java
are very different. But it seems counter-intuitive to actually have to type out .class
when you have already typed out the class name.
If there are static methods on the class, then you type MyClass.staticMethod()
, not MyClass.class.staticMethod()
.
This might be a pointless question, but I wanted to see if there was anyone out there that could enlighten me.
Because classes and variables do not share a namespace in Java, which means you can have variables which have the same name as an existing class. This statement:
String Integer = "Integer";
is completely legal and creates a new String variable named Integer
even though there is a class Integer
.
An example which shows that using the class name as a Class object would be ambiguous:
Class Integer = "Integer".getClass();
System.out.println(Integer.getName());
Would this print "java.lang.Integer" or "java.lang.String"?
But what if the variable Class Integer
would simply shadow the definition of the class Integer
?
Do you consider shadowing a good thing? It often creates confusion and nasty surprises. But this is of course debatable. Also, new Integer(42)
(constructor String(int) is undefined) now becomes a runtime error instead of a compile-time error.
But what if we would simply forbid to name variables after existing classes?
There are quite a lot of classes in the standard library. That would really shrink down the namespace of available variable names.
But then what if we only forbid to name variables after classes which are import
ed in the current .java file?
...and then you add a new import and your code doesn't compile anymore?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With