Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize dynamic Agent in Java

Shulou Source: shulou.com Published: 2022-06-02 10:27:20 10月04日 Update

Java in how to achieve dynamic agents, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Jdk dynamic agent

Realization principle: using bytecode technology to generate new class files to achieve dynamic proxy effect.

How are the new class files organized? Because the proxy target is the interface, it is done by implementing the interface and continuing the proxy class. Take a look at the following example to make it easier to understand.

Demo interface

Public interface PeoPleInterface {void say () throws Throwable;}

Implementation class

Public class GrilPeoPle implements PeoPleInterface {@ Override public void say () {System.out.println ("women say");}}

Proxy class

Public class PeoPleInvacationHandler implements InvocationHandler {private Object obj; public PeoPleInvacationHandler (Object obj) {this.obj = obj;} @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {System.out.println ("Human beginning"); Object invoke = method.invoke (obj, args); System.out.println ("Human end"); return invoke;}}

The resulting class. This class is the implementation principle of $Proxy0. This class is generated by bytecode.

Public class PeoPleProxy extends PeoPleInvacationHandler implements PeoPleInterface {public PeoPleProxy (Object obj) {super (obj);} @ Override public void say () throws Throwable {/ / call the target method super.invoke (this,PeoPleInterface.class.getMethod ("say", null), null);} public static void main (String [] args) {PeoPleInterface grilPeoPle = new GrilPeoPle (); PeoPleProxy proxy = new PeoPleProxy (grilPeoPle) Try {proxy.say ();} catch (Throwable throwable) {throwable.printStackTrace ();} is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Tags: Agents dynamic interfaces human principles bytes files goals help generation clarity examples content women for this that is technology effects articles novice Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Information Xiaomi Microsoft Shulou Technology