Thursday, June 15, 2017

byte buddy getting started


I use this pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.pierre</groupId>
  <artifactId>bytebuddytest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
   <dependency>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
    <version>1.7.0</version>
   </dependency>
  </dependencies>
</project>



and I run this Java code, as from the homepage http://bytebuddy.net/#/

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;

public class HelloWorld {
 public static void main(String[] args) throws InstantiationException, IllegalAccessException {
  HelloWorld helloWorld = new HelloWorld();
  helloWorld.testHello();

 }

 public void testHello() throws InstantiationException, IllegalAccessException {
  Class dynamicType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.named("toString"))
    .intercept(FixedValue.value("Hello World!")).make().load(getClass().getClassLoader()).getLoaded();

  System.out.println(dynamicType.newInstance().toString());
 }
}



It works! Exciting!



No comments: