gpt4 book ai didi

Java-实例化

转载 作者:行者123 更新时间:2023-12-01 18:55:47 24 4
gpt4 key购买 nike

我正在尝试创建一个我不完全确定类类型的新类。这可以用我的代码更好地解释:

private static Class[] Packets = new Class[]
{
KeepAlivePacket.class, // 0x00
LoginRequestPacket.class, // 0x01
HandshakePacket.class, // 0x02
}
.......

class HandshakePacket extends TCPPacket
{
public HandshakePacket()
{

}
byte protocolVersion;
String username;
String host;
int port;
@Override
public void writePacketData(DataOutputStream os) throws IOException {
os.write(id);
os.writeByte(protocolVersion);
writeString(os, username);
writeString(os, host);
os.writeInt(port);
}
@Override
public void readPacketData(DataInputStream is) throws IOException {
protocolVersion = is.readByte();
username = readString(is,16);
host = readString(is,16);
port = is.readInt();
}
@Override
public void setId(byte id)
{
this.id = id;
}
}

.......
public static TCPPacket getNewPacket(int i)
{
try
{
Class var1 = (Class)Packets[i];
return var1 == null ? null : (TCPPacket)var1.newInstance(); <-- error on this line
}
catch (Exception var2)
{
var2.printStackTrace();
System.out.println("Skipping packet with id " + i);
return null;
}
}

对于任何想知道 TCPPacket 是什么的人:

package vc.voidwhisperer.proxy.packet;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class TCPPacket {
public TCPPacket()
{

}
public byte id = 0;
public void writePacketData(DataOutputStream os) throws IOException
{

}
public void readPacketData(DataInputStream is) throws IOException
{

}
public void setId(byte id)
{

}
}

如您所见,我正在尝试实例化一个新对象,但我无法完全确定类类型是什么。然而,它抛出了这个异常:

java.lang.InstantiationException: vc.voidwhisperer.proxy.packet.Packet$HandshakePacket
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at vc.voidwhisperer.proxy.packet.Packet.getNewPacket(Packet.java:2509)
at vc.voidwhisperer.proxy.UserConnection.run(UserConnection.java:52)

最佳答案

对此进行反射(reflection)是多余的。

就这么做

switch (i) {
case 0: return new KeepAlivePacket();
case 1: return new LoginRequestPacket();
case 2: return new HandshakePacket();
default: throw new IllegalArgumentException();
}

最好将 i 替换为枚举。

这将为您带来静态类型和签名检查的优势,使您的代码更易于维护,并避免所有掩盖异常的反射性废话。

关于Java-实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14073034/

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