1. Overview
1.概述
Simply put, ByteBuddy is a library for generating Java classes dynamically at run-time.
简单地说,ByteBuddy是一个用于在运行时动态生成Java类的库。
In this to-the-point article, we’re going to use the framework to manipulate existing classes, create new classes on demand, and even intercept method calls.
在这篇开门见山的文章中,我们将使用该框架来操作现有的类,按需创建新的类,甚至拦截方法调用。
2. Dependencies
2.依赖性
Let’s first add the dependency to our project. For Maven-based projects, we need to add this dependency to our pom.xml:
首先,让我们把这个依赖关系添加到我们的项目中。对于基于Maven的项目,我们需要在pom.xml中添加该依赖项。
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.12.13</version>
</dependency>
For a Gradle-based project, we need to add the same artifact to our build.gradle file:
对于基于Gradle的项目,我们需要在build.gradle文件中添加同样的工件。
compile net.bytebuddy:byte-buddy:1.12.13
The latest version can be found on Maven Central.
最新版本可以在Maven Central上找到。
3. Creating a Java Class at Runtime
3.在运行时创建一个Java类
Let’s start by creating a dynamic class by subclassing an existing class. We’ll have a look at the classic Hello World project.
让我们先通过子类化一个现有的类来创建一个动态类。我们来看看经典的Hello World项目。
In this example, we create a type (Class) that is a subclass of Object.class and override the toString() method:
在这个例子中,我们创建了一个类型(Class),它是Object.class的子类,并覆盖了toString()方法。
DynamicType.Unloaded unloadedType = new ByteBuddy()
.subclass(Object.class)
.method(ElementMatchers.isToString())
.intercept(FixedValue.value("Hello World ByteBuddy!"))
.make();
What we just did was to create an instance of ByteBuddy. Then, we used the subclass() API to extend Object.class, and we selected the toString() of the super class (Object.class) using ElementMatchers.
我们刚才所做的是创建一个ByteBuddy的实例。subclass() API来扩展Object.class,并使用ElementMatchers来选择超类(Object.class)的toString()。
Finally, with the intercept() method, we provided our implementation of toString() and return a fixed value.
最后,通过intercept()方法,我们提供了toString()的实现,并返回一个固定值。
The make() method triggers the generation of the new class.
make() 方法触发了新类的生成。
At this point, our class is already created but not loaded into the JVM yet. It is represented by an instance of DynamicType.Unloaded, which is a binary form of the generated type.
在这一点上,我们的类已经创建,但还没有加载到JVM中。它由DynamicType.Unloaded的一个实例表示,它是生成类型的二进制形式。
Therefore, we need to load the generated class into the JVM before we can use it:
因此,我们需要在使用它之前将生成的类加载到JVM中。
Class<?> dynamicType = unloadedType.load(getClass()
.getClassLoader())
.getLoaded();
Now, we can instantiate the dynamicType and invoke the toString() method on it:
现在,我们可以实例化dynamicType并对其调用toString()方法。
assertEquals(
dynamicType.newInstance().toString(), "Hello World ByteBuddy!");
Note that calling dynamicType.toString() will not work since that will only invoke the toString() implementation of ByteBuddy.class.
注意,调用dynamicType.toString()不会起作用,因为这只会调用ByteBuddy.class的toString()实现。
The newInstance() is a Java reflection method that creates a new instance of the type represented by this ByteBuddy object; in a way similar to using the new keyword with a no-arg constructor.
newInstance()是一个Java反射方法,它创建了一个由这个ByteBuddy对象代表的类型的新实例;其方式类似于使用new关键字的无参数构造函数。
So far, we’ve only been able to override a method in the super class of our dynamic type and return fixed value of our own. In the next sections, we will look at defining our method with custom logic.
到目前为止,我们只能在我们的动态类型的超类中覆盖一个方法并返回我们自己的固定值。在接下来的章节中,我们将研究如何用自定义逻辑来定义我们的方法。
4. Method Delegation and Custom Logic
4.方法委托和自定义逻辑
In our previous example, we return a fixed value from the toString() method.
在我们之前的例子中,我们从toString()方法中返回一个固定值。
In reality, applications require more complex logic than this. One effective way of facilitating and provisioning custom logic to dynamic types is the delegation of method calls.
在现实中,应用程序需要比这更复杂的逻辑。促进和提供自定义逻辑到动态类型的一个有效方法是方法调用的委托。
Let’s create a dynamic type that subclasses Foo.class which has the sayHelloFoo() method:
让我们创建一个子类Foo.class的动态类型,它有sayHelloFoo()方法。
public String sayHelloFoo() {
return "Hello in Foo!";
}
Furthermore, let’s create another class Bar with a static sayHelloBar() of the same signature and return type as sayHelloFoo():
此外,让我们创建另一个类Bar,其静态sayHelloBar()的签名和返回类型与sayHelloFoo()相同。
public static String sayHelloBar() {
return "Holla in Bar!";
}
Now, let’s delegate all invocations of sayHelloFoo() to sayHelloBar() using ByteBuddy‘s DSL. This allows us to provide custom logic, written in pure Java, to our newly created class at runtime:
现在,让我们使用ByteBuddy的DSL将sayHelloFoo()的所有调用委托给sayHelloBar。这允许我们在运行时向我们新创建的类提供用纯Java编写的自定义逻辑。
String r = new ByteBuddy()
.subclass(Foo.class)
.method(named("sayHelloFoo")
.and(isDeclaredBy(Foo.class)
.and(returns(String.class))))
.intercept(MethodDelegation.to(Bar.class))
.make()
.load(getClass().getClassLoader())
.getLoaded()
.newInstance()
.sayHelloFoo();
assertEquals(r, Bar.sayHelloBar());
Invoking the sayHelloFoo() will invoke the sayHelloBar() accordingly.
调用sayHelloFoo()将相应调用sayHelloBar()。
How does ByteBuddy know which method in Bar.class to invoke? It picks a matching method according to the method signature, return type, method name, and annotations.
ByteBuddy如何知道要调用Bar.class中的哪个方法?它根据方法签名、返回类型、方法名称和注解挑选一个匹配的方法。
The sayHelloFoo() and sayHelloBar() methods do not have the same name, but they have the same method signature and return type.
sayHelloFoo()和sayHelloBar()方法的名字不一样,但它们有相同的方法签名和返回类型。
If there is more than one invocable method in Bar.class with matching signature and return type, we can use @BindingPriority annotation to resolve the ambiguity.
如果在Bar.class中存在一个以上的可调用方法,其签名和返回类型相匹配,我们可以使用@BindingPriority注解来解决歧义。
@BindingPriority takes an integer argument – the higher the integer value, the higher the priority of calling the particular implementation. Thus, sayHelloBar() will be preferred over sayBar() in the code snippet below:
@BindingPriority需要一个整数参数–整数值越高,调用特定实现的优先级就越高。因此,在下面的代码片段中,sayHelloBar()将优先于sayBar()。
@BindingPriority(3)
public static String sayHelloBar() {
return "Holla in Bar!";
}
@BindingPriority(2)
public static String sayBar() {
return "bar";
}
5. Method and Field Definition
5.方法和领域的定义
We have been able to override methods declared in the super class of our dynamic types. Let’s go further by adding a new method (and a field) to our class.
我们已经能够覆盖在我们的动态类型的超类中声明的方法。让我们更进一步,给我们的类添加一个新的方法(和一个字段)。
We will use Java reflection to invoke the dynamically created method:
我们将使用Java反射来调用动态创建的方法。
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.name("MyClassName")
.defineMethod("custom", String.class, Modifier.PUBLIC)
.intercept(MethodDelegation.to(Bar.class))
.defineField("x", String.class, Modifier.PUBLIC)
.make()
.load(
getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
Method m = type.getDeclaredMethod("custom", null);
assertEquals(m.invoke(type.newInstance()), Bar.sayHelloBar());
assertNotNull(type.getDeclaredField("x"));
We created a class with the name MyClassName that is a subclass of Object.class. We then define a method, custom, that returns a String and has a public access modifier.
我们创建了一个名为MyClassName的类,它是Object.class的一个子类。然后我们定义了一个方法,custom,,它返回一个String,并且有一个public访问修饰符。
Just like we did in previous examples, we implemented our method by intercepting calls to it and delegating them to Bar.class that we created earlier in this tutorial.
就像我们在以前的例子中所做的那样,我们通过拦截对它的调用并将其委托给我们在本教程中早先创建的Bar.class来实现我们的方法。
6. Redefining an Existing Class
6.重新定义一个现有的类
Although we have been working with dynamically created classes, we can work with already loaded classes as well. This can be done by redefining (or rebasing) existing classes and using ByteBuddyAgent to reload them into the JVM.
虽然我们一直在处理动态创建的类,但我们也可以处理已经加载的类。这可以通过重新定义(或重新设置)现有的类并使用ByteBuddyAgent将其重新加载到JVM中来实现。
First, let’s add ByteBuddyAgent to our pom.xml:
首先,让我们把ByteBuddyAgent添加到我们的pom.xml。
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-agent</artifactId>
<version>1.7.1</version>
</dependency>
The latest version can be found here.
最新的版本可以在这里找到。
Now, let’s redefine the sayHelloFoo() method we created in Foo.class earlier:
现在,让我们重新定义我们之前在Foo.class中创建的sayHelloFoo()方法。
ByteBuddyAgent.install();
new ByteBuddy()
.redefine(Foo.class)
.method(named("sayHelloFoo"))
.intercept(FixedValue.value("Hello Foo Redefined"))
.make()
.load(
Foo.class.getClassLoader(),
ClassReloadingStrategy.fromInstalledAgent());
Foo f = new Foo();
assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");
7. Conclusion
7.结论
In this elaborate guide, we’ve looked extensively into the capabilities of the ByteBuddy library and how to use it for efficient creation of dynamic classes.
在这份详尽的指南中,我们广泛地研究了ByteBuddy库的功能以及如何使用它来有效地创建动态类。
Its documentation offers an in-depth explanation of the inner workings and other aspects of the library.
其文档对图书馆的内部运作和其他方面提供了深入的解释。
And, as always, the complete code snippets for this tutorial can be found over on Github.
而且,像往常一样,本教程的完整代码片段可以在Github上找到over。