gpt4 book ai didi

使用 new 运算符和 .class.newInstance() 方法创建 java 对象

转载 作者:行者123 更新时间:2023-12-01 10:13:19 26 4
gpt4 key购买 nike

我有以下代码片段

public class Test2 {

public static void main(String[] args) {

Test test = null;
try {
test = Test.class.newInstance();
if(test!=null)
System.out.println("test class instance created");
System.out.println(test.getA()+"\t"+test.getB());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

public class Test {

private int a;
private int b;

public Test() {
// TODO Auto-generated constructor stub
System.out.println("test class constructor executed");
}

public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}

static {
System.out.println("static block of Test class exectuted");
}


{
System.out.println("test class IIB executed");
}

我正在尝试使用

创建 Test 类的实例
test = Test.class.newInstance(); 

我的问题:这是正确的方法吗?

两者之间有什么区别

Test t1 = new Test();

以及上述方法?

当我运行 Test2 类时,我得到以下信息:

static block of Test class exectuted
test class IIB executed
test class constructor executed
test class instance created
0 0

最佳答案

is this the correct way to do??

不,事实并非如此。使用。因为Class.newInstance() :

Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler.

关于使用 new 运算符和 .class.newInstance() 方法创建 java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36039462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com