我正在尝试创建一个我不完全确定类类型的新类。这可以用我的代码更好地解释:
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)