简体   繁体   English

new运算符和Class.newInstance()之间有什么区别?

[英]What is the difference between the new operator and Class.newInstance()?

What is the difference between new operator and Class.forName(...).newInstance() ? new运算符和Class.forName(...).newInstance()之间有什么区别Class.forName(...).newInstance() Both of them create instances of a class, and I'm not sure what the difference is between them. 它们都创建了一个类的实例,我不确定它们之间的区别。

The new operator creates a new object of a type that's known statically (at compile-time) and can call any constructor on the object you're trying to create. new运算符创建一个静态已知类型的新对象(在编译时),并且可以调用您尝试创建的对象上的任何构造函数。 It's the preferred way of creating an object - it's fast and the JVM does lots of aggressive optimizations on it. 这是创建对象的首选方式 - 它很快,JVM对它进行了大量的积极优化。

Class.forName().newInstance() is a dynamic construct that looks up a class with a specific name. Class.forName().newInstance()是一个动态构造,用于查找具有特定名称的类。 It's slower than using new because the type of object can't be hardcoded into the bytecode, and because the JVM might have to do permissions checking to ensure that you have the authority to create an object. 它比使用new慢,因为对象的类型不能硬编码到字节码中,并且因为JVM可能必须进行权限检查以确保您有权创建对象。 It's also partially unsafe because it always uses a zero-argument constructor, and if the object you're trying to create doesn't have a nullary constructor it throws an exception. 它也部分不安全,因为它总是使用零参数构造函数,如果你想要创建的对象没有一个无效的构造函数,它会抛出一个异常。

In short, use new if you know at compile-time what the type of the object is that you want to create. 简而言之,如果您在编译时知道要创建的对象类型,请使用new Use Class.forName().newInstance() if you don't know what type of object you'll be making. 如果您不知道要创建的对象类型,请使用Class.forName().newInstance()

Class.forName("your class name").newInstance() is useful if you need to instantiate classes dynamically, because you don't have to hard code the class name to create an object. Class.forName("your class name").newInstance()如果你需要动态地实例化类, Class.forName("your class name").newInstance()很有用,因为你不必硬编码类名来创建一个对象。

Imagine a scenario where you load classes dynamically from a remote source. 想象一下从远程源动态加载类的场景。 You will know their names but can't import them at compile time. 您将知道他们的名字,但无法在编译时导入它们。 In this case you can't use new to create new instances. 在这种情况下,您无法使用new来创建新实例。 That's (one reason) why Java offers the newInstance() method. 这是(一个原因)Java提供newInstance()方法的原因。

Class.forName只能调用默认构造函数(没有参数),并且可以在运行时提供类名,例如从配置文件中读取的db-driver名称。

主要的区别是Class.forName('your class name').newInstance()是动态的,因为类型不需要硬编码到代码中。

Class.forName("your class name").newInstance() is used when you want to get an instance form a class work similar to new , but it is useful when you want to get instance from a class in a jar file or remote server and you can not import it in compile time. Class.forName("your class name").newInstance()当你想要一个类似于new的类工作时,使用Class.forName("your class name").newInstance() ,但是当你想从jar文件或远程的类中获取实例时它很有用服务器,你不能在编译时导入它。

ex: Class.forName("YOUR JDBC DRIVER").newInstance() , you can not import the JDBC class at compile time. 例如: Class.forName("YOUR JDBC DRIVER").newInstance() ,你不能在编译时导入JDBC类。

Class.forName('myClass').newInstance() loads the class if not already loaded. Class.forName('myClass').newInstance()加载该类(如果尚未加载)。 Here it calls the initial constructor and only executes the static part of the constructor. 这里它调用初始构造函数,只执行构造函数的静态部分。

The new operator is used to initialize new objects. new运算符用于初始化新对象。

You can create many instances from both the new operator and Class.forName() difference is the 2nd time you create a newInstance() static blocks will not get initialized. 您可以从new运算符和Class.forName()创建许多实例。区别是第二次创建newInstance()静态块将不会被初始化。

A good example of Class.forName('myClass).newInstance() is the JDBC driver Class.forName('myClass).newInstance()一个很好的例子是JDBC驱动程序

Class.forName("com.mysql.JDBC.Driver").newInstance()

Class.forName will do a lookup to find the Class object for YourClass . Class.forName将执行查找以查找YourClassClass对象。

Using the new operator should be the same as YourClass.class.newInstance() . 使用new运算符应与YourClass.class.newInstance()相同。

While both effectively do the same thing, you should use the new operator instead of doing Class.forName('class').getInstance(). 虽然两者都有效地做同样的事情,但你应该使用new运算符而不是使用Class.forName('class')。getInstance()。 The latter uses the reflection API to lookup the class at runtime. 后者使用反射API在运行时查找类。 By using the new operator, the VM will know beforehand that you want to use that class and thus be more efficient. 通过使用new运算符,VM将事先知道您要使用该类,从而提高效率。

Let's assume com.statckoverflow.Test 我们假设com.statckoverflow.Test

Class.forName - It will load the Test class and return the Class class object which contains the metadata of Test class Like name, package, constructor, annotations, methods, fields. Class.forName - 它将加载Test类并返回包含Test类元数据的Class类对象,如name,package,constructor,annotations,methods,fields。

newInstance() - Used to instantiate new objects using Java Reflection. newInstance() - 用于使用Java Reflection实例化新对象。 Internally zero parameter constructor will be called on the Test class. 将在Test类上调用内部零参数构造函数。 This means Class class object will create the Test class object by calling the zero parameter constructor, We can use the reflection for details of Test class. 这意味着Class类对象将通过调用零参数构造函数来创建Test类对象。我们可以使用反射来获取Test类的详细信息。 Like Constructors, methods etc. 像构造函数,方法等

new operator - Creates the New Object for the class instantiate the Class and can call their constructors. new operator - 为类创建新对象实例化Class并可以调用它们的构造函数。

If no zero argument constructor of an object it will also create an object and it will not throw any exception, please find the below code snippets. 如果没有对象的零参数构造函数,它也会创建一个对象并且不会抛出任何异常,请查找下面的代码片段。

try {
    Class o = Class.forName("com.myCompany.MyClass");

    Constructor m = o.getConstructor(Integer.class,String.class);
    m.newInstance(new Integer(0),new String(""));

} catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InstantiationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (NoSuchMethodException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

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

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