How to subclass an abstract class with 1+ args constructor using ByteBuddy

How to subclass an abstract class with 1+ args constructor using ByteBuddy



I would like to proxy java.net.HttpURLConnection which has one constructor: HttpURLConnection(URL u). How can I subclass such a class with ByteBuddy without creating custom "Empty" class with the non-arg constructor?


HttpURLConnection(URL u)


new ByteBuddy().subclass(HttpURLConnection.class)
.method(ElementMatchers.any())
.intercept(InvocationHandlerAdapter.of(proxyHandler))
.make()
.load(HttpURLConnection.class.getClassLoader())
.getLoaded()
.newInstance();



Currently, it fails due to


Caused by: java.lang.NoSuchMethodException: net.bytebuddy.renamed.java.net.HttpURLConnection$ByteBuddy$Mr8B9wE2.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)



I would like to delegate a custom URL to that super constructor it is possible.


URL



But if I create a custom class


public class ProxiedHttpURLConnection extends HttpURLConnection

protected ProxiedHttpURLConnection()
super(null); // <---





and use that one in new ByteBuddy().subclass(ProxiedHttpURLConnection.class) it works fine. There is simple issue with a contractor, not quite sure how to do it.


new ByteBuddy().subclass(ProxiedHttpURLConnection.class)




1 Answer
1



You can define a custom constructor and invoke a specific super constructor using the MethodCall instrumentation, e.g.


MethodCall


builder = builder.defineConstructor(Visibility.PUBLIC)
.intercept(MethodCall.invoke(HttpURLConnection.class.getDeclaredConstructor(URL.class))
.with((Object) null))



By default, Byte Buddy immitates the super class constructors, you can therefore lookup a declared constructor that takes a URL and provide the null argument manually.



You can avoid this creation by defining a ConstructorStrategy as a second argument to subclass.


ConstructorStrategy


subclass






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế