简体   繁体   English

Myclass.class与new MyClass()有什么区别?

[英]What is difference between Myclass.class vs new MyClass()?

Team, While learning java (specially generics), i could see two different parameter in the method (.class and object reference) . 团队,在学习Java(特别是泛型)时,我可以在方法中看到两个不同的参数(.class和object reference)。 When to use .class option and new myclass()? 什么时候使用.class选项和新的myclass()? give me some example to understand 给我一些例子来理解

new MyClass(): will create an instance/object of type MyClass new MyClass():将创建MyClass类型的实例/对象

MyClass.class: is a "class literal" - a simple way of getting the Class for a particular type. MyClass.class:是“类文字”-一种获取特定类型的Class的简单方法。 in order to extract the metadata about the class such as fields and methods. 为了提取有关类的元数据,例如字段和方法。

Refer to the Java Language Specification for more details. 有关更多详细信息,请参考Java语言规范 (15.8.2 Class Literals) (15.8.2类文字)

 MyClass obj = new MyClass();

it returns a new object of type MyClass and will have all the global variables and methods defined in MyClass but, 它返回一个MyClass类型的新对象,并将具有MyClass中定义的所有全局变量和方法,但是,

Class obj1  = MyClass.class;

here obj1 cannot be treated as an object of MyClass. 此处obj1不能视为MyClass的对象。 obj1 is an object of Class.java(a class pre defined in java). obj1是Class.java(java中预定义的类)的对象。 It does not have all the informations of MyClass. 它没有MyClass的所有信息。 but some methods defined in Class.java has some generic information of MyClass like: object.name will give MyClass 但是Class.java中定义的某些方法具有MyClass的一些常规信息,例如: object.name将提供MyClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM