[英]Class.forName(“org.MyClass”) and MyClass.class differences
Class.forName("org.MyClass")
and MyClass.class
both require class name. Class.forName("org.MyClass")
和MyClass.class
都需要类名。 So, what does it mean when we say Class.forName("org.MyClass")
is used when we don't know the name of the class at compile time and MyClass.class
is used when we know the name of the class? 那么,当我们在编译时不知道类名而使用Class.forName("org.MyClass")
时,而当我们知道类名称时就使用MyClass.class
意味着什么呢?
How are these different from obj.getClass()
? 这些与obj.getClass()
有何不同?
MyClass.class
is generally known at compile time to be a given class. MyClass.class
通常在编译时是给定的类。
obj.getClass()
is used when an object is known but not its class, or if the object is a refiable generic type, to get a class. obj.getClass()
在已知对象但不知道其类时使用,或者如果该对象是可仿造的泛型类型,则使用obj.getClass()
获取类。
Class.forName("org.YourClass")
is needed if you know the name of the class (ie the name was passed over the network or was otherwise obtained as a string) without an instance of the class, or the class's identity known at compile-time. 如果您知道类的名称(即,该名称是通过网络传递的,或者是以字符串形式获得的),而没有该类的实例,或者您知道该类的标识,则需要Class.forName("org.YourClass")
编译时。
You already gave the answer yourself: when you use MyClass.class
, then the compiler needs to know what MyClass
is, so you'll need to have MyClass
in your classpath at compile time; 您已经自己给出了答案:当您使用MyClass.class
,编译器需要知道MyClass
是什么,因此您需要在编译时将MyClass
放入类路径中。 whereas when you use Class.forName("org.MyClass")
, the class does not need to be in the classpath at compile time - only at runtime. 相反,当您使用Class.forName("org.MyClass")
,该类无需在编译时位于类路径中-只需在运行时即可。
This is used for example for JDBC drivers. 例如,这用于JDBC驱动程序。 You write your code to use the JDBC API, but you don't need to specify at compile time which JDBC driver you're going to use. 您可以编写代码来使用JDBC API,但无需在编译时指定要使用的JDBC驱动程序。 This also allows you to switch to another JDBC driver without recompiling your own code. 这也使您可以切换到另一个JDBC驱动程序,而无需重新编译自己的代码。
obj.getClass()
gets the Class
object for obj
. obj.getClass()
获取obj
的Class
对象。
Class.forName("org.MyClass") equal to MyClass
MyClass.class equal to Class<MyClass>
with MyClass.class
you get the class at compile-time. 使用MyClass.class
可以在编译时获取类。
and with Class.forName("org.MyClass")
at runtime. 并在运行时使用Class.forName("org.MyClass")
。
Your normaly pass a value to Class#forName and don't hardcode the String. 通常,您将一个值传递给Class#forName,并且不要对字符串进行硬编码。 If it's hard-coded, uses .class
如果是硬编码,请使用.class
MyClass.class
: MyClass.class
:
Class<MyClass>
, hence newInstance()
returns MyClass
. 可以分配给Class<MyClass>
,因此newInstance()
返回MyClass
。 Class.forName("org.MyClass")
: Class.forName("org.MyClass")
:
Class<MyClass>
, but Class<?>
instead, hence newInstance()
returns Object
. 无法分配给Class<MyClass>
,而只能分配给Class<MyClass>
Class<?>
,因此newInstance()
返回Object
。 ClassNotFoundException
which needs to be handled. 引发需要处理的检查异常ClassNotFoundException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.