Foo.class what does it do?

2019-06-16 07:37发布

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?

2条回答
混吃等死
2楼-- · 2019-06-16 07:50

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; 
查看更多
3楼-- · 2019-06-16 08:04

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.

查看更多
登录 后发表回答