我想創建一個新的類,我不完全確定類類型的東西。這可能與我的代碼可以更好地解釋說:Java - 實例化錯誤?
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)
{
}
}
正如你可以看到我試圖instaniate一個新的對象,我不能完全確定類的類型。然而,它正在吐出這個例外:
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)
InstantiationException包裝通常在其後打印的真正異常。你能提供實際的例外嗎?它還表示發生異常時調用Packet.HandshakePacket的構造函數。你能提供導致異常的類的源代碼並告訴使用它到底發生了哪一行嗎? –
順便說一句'setId'沒有設置'id'字段嗎? –
將'HandshakePacket'的相關代碼包含到您的問題中,包括其構造函數。我會推薦複製/粘貼代碼(而不是手動輸入問題)。 – Perception