简体   繁体   中英

Foo.class what does it do?

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?

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.

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. eg

Class c1 = String.class; 

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