简体   繁体   中英

A Java reflection wrapper code generator?

I'd like to work with a class that is only available in my runtime environment, and I don't have any .java or .class files of it. The only way to use it AFAIK is through reflection.

What I already did, is to write a small program to get the Class instance of my target class, iterate through its public methods/fields and get their signature (similar as in this program ). This will give me a skeleton of a .java source file. Then I manually filled the bodies of those methods so that they call the real methods using reflection. The so-made Java file is compiled by javac, together with my user code. This way I could use the target class without filling my code with Method/Field getters.

Here are my questions:

  • Is there a specific term for what I'm trying to do? ("Java reflection wrapper code generator" maybe?)
  • Is there a tool that automates the task I did manually above?
  • If not, what are the challenges in building such a tool?

What you try to do is a Proxy Class. Lot of framework use it to inject some automation, transactions etc... Java EE, Spring, for example.

There are 2 ways: The simple one with java.lang.reflect.Proxy, but it has a constraints: your class must implements an interface, and only method in Interface can be called.

The more complex one rely on bytecode generation, you can use the Mockito framework that generate all what you need: it is intended for tests, but can be also used to generate any kind of class wich override an existing one.

I may complete my answer with example if you need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM