简体   繁体   中英

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

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?

I think there are a couple of reasons. The first was mentioned in the comment by peeskillet, where the compiler has to deal with instantiation of a new type of the object:

MyClass myClassInstance = new MyClass();

The other is that there is actually an object ( Class<?> ) which represents a class of a type - its not just "that class". This can be used as an argument to other methods, so you need a way to distinguish between an attempt to create a new instance (above) and a reference to the Class<?> of the object.

Whether this was a good idea, or if it could be simplified is certainly up for debate :) Note that Java arose from strong roots in C/C++, so there are most certainly things within it that came from that line of thinking - there's always the possibility for "seemed like a good idea at the time"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM