Foo.class 有什么作用?
我正在查看一些Java代码,并且有这样的代码是我经常看到的。
Foo.class
这是用来指示类的类型吗? 的类似吗
Foo.GetType();
typeof(Foo);
与C# 中
?它的用途是什么?它的意义是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,Java 中的
Foo.class
相当于 C# 中的typeof(Foo)
。请参阅JLS 的第 15.8.2 节 有关类文字的更多信息。它与在引用上调用
GetType()
不同,后者获取对象的执行时间类型。 Java 中的等效项是someReference.getClass()
。您在 Java 代码中比在 C# 中更频繁地看到它的原因之一是与泛型有关。类似这样的情况并不完全不寻常:
这允许执行时访问类以进行反射等。由于类型擦除,这仅在 Java 中是必需的,因此泛型类型的对象不能通常在执行时确定其类型参数。
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.
java中有一个特殊的类,称为Class。它继承对象。它的实例代表java运行时的类和接口,也代表enum、array、原始Java类型(boolean、byte、char、short、int、long、float、double)和关键字void 。当一个类被加载时,或者JVM调用类加载器的defineClass()方法时,JVM会创建一个Class对象。
Java允许我们通过多种方式创建一个类对应的Class对象,
.class 就是其中之一。
例如
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.