I m looking at some Java code, and there is this code that I see often.
Foo.class
This is being used to to indicate the Type of the class? is that similar to
Foo.GetType();
typeof(Foo);
in C# ?
What is it being used for ? and what s the meaning of it?
there is special class in java called Class . it inherits Object. its instance represents the classes and interfaces in java runtime, and also represents enum、array、primitive Java types(boolean, byte, char, short, int, long, float, double)and the key word void. when a class is loaded, or the method defineClass() of class loader is called by JVM, then JVM creates a Class object.
Java allows us to create a corresponding Class object of a class in many ways, and .class is one of them. e.g.
Yes,
Foo.class
in Java is equivalent totypeof(Foo)
in C#. See section 15.8.2 of the JLS for more information on class literals.It's not the same as calling
GetType()
on a reference, which gets the execution time type of an object. The Java equivalent of that issomeReference.getClass()
.One reason you may see it more often in Java code than in C# is in relation to generics. It's not entirely unusual to have something like:
This allows execution-time access to the class for reflection etc. This is only necessary in Java due to type erasure, whereby an object of a generic type can't normally determine its type arguments at execution time.