Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foo.class what does it do?

Tags:

java

c#

types

class

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?

like image 937
DarthVader Avatar asked Oct 17 '11 06:10

DarthVader


2 Answers

Yes, Foo.class in Java is equivalent to typeof(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 is someReference.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:

public class Generic<T>
{
    private final Class<T> clazz;

    public Generic(Class<T> clazz)
    {
        this.clazz = clazz;
    }
}

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.

like image 93
Jon Skeet Avatar answered Oct 13 '22 16:10

Jon Skeet


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.

Class c1 = String.class; 
like image 37
ojlovecd Avatar answered Oct 13 '22 16:10

ojlovecd