i cant claim that this will always work, you should always use copy-constructor as far as you can but in some cases (like you dont have access/right to change code or dont want to produce complexities) you can use this (example:),
import java.lang.reflect.Field;
import java.net.Socket;
public class SmarterSocket extends Socket {
public SmarterSocket(Socket s) {
super(); // default constructor for super instance
// will iterate over public/private fields of "s" (superclass not included)
for(Field f : s.getClass().getDeclaredFields()){
try {
f.setAccessible(true);
f.set(this,f.get(s));
}catch (Exception ignored){}
}
}
public void doSmartStuff(){
System.out.println("smarter");
}
}
...
public static void main(String[] args){
try {
Socket s = new Socket();
s.connect(new InetSocketAddress("stackoverflow.com",80));
SmarterSocket ss = new SmarterSocket(s);
ss.close();
System.out.println("is SmartSocket closed: " + ss.isClosed());
System.out.println("is Socket closed: " + s.isClosed());
s.getOutputStream().write("hellow".getBytes()); // write to s
} catch (IOException e) {
e.printStackTrace();
}
}
is SmartSocket closed: true
is Socket closed: false
java.io.IOException: Socket Closed
at java.base/java.net.AbstractPlainSocketImpl.getOutputStream(AbstractPlainSocketImpl.java:489)
at java.base/java.net.Socket$3.run(Socket.java:972)
at java.base/java.net.Socket$3.run(Socket.java:970)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.net.Socket.getOutputStream(Socket.java:969)
at Main.main(Main.java:47)
i used above example for hooking some monitors inside socket
but you have to be cautious:
1- reflection is complex: sometimes fields are being used for synchronization or more sophisticated stuff, you probably shouldn't update static (or more clearly static final) fields, you should have proper knowledge about internals of the class you are proxying it,and do some heavy tests to make sure everything is going smoothly
2- reflection is slow in runtime: test it, if it suit you let it be there
this.superwould not be a class but an instance. And there is no such thing as thesuperinstance, because super is the instance itself.