英文:
Java - how to call a generic instance method
问题
class Connection
{
private Socket m_socket;
private ObjectOutputStream m_send;
private ObjectInputStream m_recv;
// Methods for initializing socket omitted
public <Type extends Serializable> Type readObject() throws IOException, ClassNotFoundException
{
return (Type)m_recv.readObject();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Connection conn = new Connection();
// 无法正常工作。
// 错误:-> 期望
ServerResponse resp = conn.readObject<ServerResponse>();
}
}
为什么我无法使用提供的类型调用readObject,而只能使用conn.readObject()调用它。
英文:
class Connection
{
private Socket m_socket;
private ObjectOutputStream m_send;
private ObjectInputStream m_recv;
// Methods for initializing socket omitted
public <Type extends Serializable> Type readObject() throws IOException, ClassNotFoundException
{
return (Type)m_recv.readObject();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Connection conn = new Connection();
// Doesn't work.
// error: -> expected
ServerResponse resp = conn.readObject<ServerResponse>();
}
}
Why I am not able to call readObject with supplied type but instead can call it using only conn.readObject()
.
答案1
得分: 0
请查看!这对我有效。
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
public class Connection {
private Socket m_socket;
private ObjectOutputStream m_send;
private ObjectInputStream m_recv;
// 初始化套接字的方法被省略
public <Type extends Serializable> Type readObject() throws IOException, ClassNotFoundException {
return (Type)m_recv.readObject();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Connection conn = new Connection();
ServerResponse resp = conn.readObject();
// 这是完整的语法
// ServerResponse resp = conn.<ServerResponse>readObject();
}
}
class ServerResponse implements Serializable {}
英文:
Check this out! It works to me.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
public class Connection {
private Socket m_socket;
private ObjectOutputStream m_send;
private ObjectInputStream m_recv;
// Methods for initializing socket omitted
public <Type extends Serializable> Type readObject() throws IOException, ClassNotFoundException {
return (Type)m_recv.readObject();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Connection conn = new Connection();
ServerResponse resp = conn.readObject();
// This is a full syntax
// ServerResponse resp = conn.<ServerResponse>readObject();
}
}
class ServerResponse implements Serializable {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论