Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you have to use .class in Java to get the Class object? Why not just the class name like in Ruby?

Tags:

java

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.

like image 475
arjabbar Avatar asked Dec 15 '22 09:12

arjabbar


1 Answers

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 imported in the current .java file?

...and then you add a new import and your code doesn't compile anymore?

like image 156
Philipp Avatar answered Apr 30 '23 01:04

Philipp