描述: 我有一个 Connection 类,其默认构造函数设置为私有(private)。可以通过静态方法创建此类。更多一些方法也是此类功能的一部分(例如 setTraits(...) 和 display())。我通过方法在主线程中创建了Connection的实例,并将其分配给了一个引用。
问题: 但是,当我尝试从此引用调用方法以访问和更改其私有(private)字段的值时,出现了 NullPointerException。我的代码有什么问题吗?
编辑,已解决:类Connection中的代码: public static Connection createConnection() {} 检查connectionCount数组的长度是否小于5。由于connectionCount数组是在顶部分配的类的长度(长度为 5),if 语句将始终返回 null 并因此导致 NullPointerException,因为连接对象从未创建并且您正在尝试访问它的字段。
类(class):
这是连接类:
public class Connection {
private int bandwidth;
private int timeLength;
private int downloadSpeed;
private int uploadSpeed;
private static Connection[] connectionCount = new Connection[5];
private Connection() {
}
public static Connection createConnection() {
if (connectionCount.length < 5) {
Connection con = new Connection();
//connectionCount[ConnectionUtils.getConArrayLength(connectionCount)] = con;
connectionCount[connectionCount.length -1] = con;
return con;
} else return null;
}
public void setTraits(int bandwidth, int timeLength, int downloadSpeed, int uploadSpeed) {
this.bandwidth = bandwidth;
this.timeLength = timeLength;
this.downloadSpeed = downloadSpeed;
this.uploadSpeed = uploadSpeed;
}
public int getBandwidth() {
return bandwidth;
}
public int getTimeLength() {
return timeLength;
}
public int getDownloadSpeed() {
return downloadSpeed;
}
public int getUploadSpeed() {
return uploadSpeed;
}
public void display() {
System.out.println("bandwidth: " + bandwidth);
System.out.println("timeLength: " + timeLength);
System.out.println("downloadSpeed: " + downloadSpeed);
System.out.println("uploadSpeed: " + uploadSpeed);
}
}
这是ConnectionUtils类,它提供了getConArrayLength(Connection[] c)方法,该方法返回指定数组的长度。 [已弃用]
public class ConnectionUtils {
public static int getConArrayLength(Connection[] c) {
return c.length;
}
}
现在,这是在第 6 行抛出 NullPointerException 的主类 (con1.setTraits(50, 60, 100_000, 2000);):
public class ConnectionManager {
public static void main(String[] args) {
Connection con1 = Connection.createConnection();
con1.setTraits(50, 60, 100_000, 2000);
con1.display();
}
}
最佳答案
private static Connection[] connectionCount = new Connection[5];
您创建一个包含 5 个元素(固定)的数组
public static Connection createConnection() {
if (connectionCount.length < 5) {
Connection con = new Connection();
//connectionCount[ConnectionUtils.getConArrayLength(connectionCount)] = con;
connectionCount[connectionCount.length -1] = con;
return con;
} else return null;
}
当您调用createConnection
时方法,检查数组的长度是否小于5,如果是,则创建一个新连接,否则返回 null
。自 5 < 5
永远不会返回 true,你的 create 方法总是返回 null
.
关于java - 在 Java 中使用 setter 方法访问通过静态方法创建的实例的私有(private)字段出错 - 该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48900665/