Всем привет! Подскажите пожалуйста как правильно наследоваться от класса DatagramSocket?
Мне нужно переопределить метод send, выкинуть от туда всё лишнее.
Что я делаю:
1. Создаю класс наследник MyDatagramSocket extends DatagramSocket
2. Переопределяю метод send,
@Override
public void send(DatagramPacket p) throws IOException {
}
3. Смотрю нативный метод send
public void send(DatagramPacket p) throws IOException {
InetAddress packetAddress = null;
synchronized (p) {
if (isClosed())
throw new SocketException("Socket is closed");
checkAddress (p.getAddress(), "send");
if (connectState == ST_NOT_CONNECTED) {
// check the address is ok wiht the security manager on every send.
SecurityManager security = System.getSecurityManager();
// The reason you want to synchronize on datagram packet
// is because you don't want an applet to change the address
// while you are trying to send the packet for example
// after the security check but before the send.
if (security != null) {
if (p.getAddress().isMulticastAddress()) {
security.checkMulticast(p.getAddress());
} else {
security.checkConnect(p.getAddress().getHostAddress(),
p.getPort());
}
}
} else {
// we're connected
packetAddress = p.getAddress();
if (packetAddress == null) {
p.setAddress(connectedAddress);
p.setPort(connectedPort);
} else if ((!packetAddress.equals(connectedAddress)) ||
p.getPort() != connectedPort) {
throw new IllegalArgumentException("connected address " +
"and packet address" +
" differ");
}
}
// Check whether the socket is bound
if (!isBound())
bind(new InetSocketAddress(0));
// call the method to send
getImpl().send(p);
}
}
4. Хочу оставить только последнюю строку, в методе send, getImpl().send(p);
5. Смотрю метод getImpl()
DatagramSocketImpl getImpl() throws SocketException {
if (!created)
createImpl();
return impl;
}
6. Смотрю класс DatagramSocketImpl, вижу что там есть метод send и он определён так
protected abstract void send(DatagramPacket p) throws IOException;
Из этого я понимаю, что вызвать его можно только из класса наследника от DatagramSocketImpl
7. Соответственно я не могу его вызвать из своего класса, да и как он вызывается из DatagramSocket тоже не понятно, потому как DatagramSocket описан так
public
class DatagramSocket implements java.io.Closeable
8. Я попробовал добраться до этого метода через reflection
Method send = DatagramSocketImpl.class.getDeclaredMethod("send", DatagramPacket.class);
send.setAccessible(true);
получилось, могу отправить. Но я не хочу это делать через reflection потому как это долго. Хочу вызывать этот метод напрямую.
Подскажите пожалуйста как правильно наследоваться от DatagramSocket, так, чтобы можно было вызывать метод DatagramSocketImpl .send(DatagramPacket p).