forked from microbean/microbean-clientproxy-bytebuddy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBBClientProxyClassGenerator.java
More file actions
253 lines (212 loc) · 10.3 KB
/
BBClientProxyClassGenerator.java
File metadata and controls
253 lines (212 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*-
*
* Copyright © 2025–2026 microBean™.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.microbean.clientproxy.bytebuddy;
import java.util.Collection;
import java.util.List;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.modifier.FieldManifestation;
import net.bytebuddy.description.modifier.MethodManifestation;
import net.bytebuddy.description.modifier.ParameterManifestation;
import net.bytebuddy.description.modifier.TypeManifestation;
import net.bytebuddy.description.type.TypeDefinition;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.DefaultMethodCall;
import net.bytebuddy.implementation.HashCodeMethod;
import net.bytebuddy.implementation.EqualsMethod;
import net.bytebuddy.implementation.FieldAccessor;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.pool.TypePool;
import static java.util.Objects.requireNonNull;
import static net.bytebuddy.description.modifier.SyntheticState.SYNTHETIC;
import static net.bytebuddy.description.modifier.Visibility.PRIVATE;
import static net.bytebuddy.description.modifier.Visibility.PUBLIC;
import static net.bytebuddy.description.type.TypeDescription.Generic.Builder.parameterizedType;
import static net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy.Default.NO_CONSTRUCTORS;
import static net.bytebuddy.implementation.MethodCall.invoke;
import static net.bytebuddy.implementation.MethodCall.invokeSelf;
import static net.bytebuddy.matcher.ElementMatchers.any;
import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy;
import static net.bytebuddy.matcher.ElementMatchers.isEquals;
import static net.bytebuddy.matcher.ElementMatchers.isFinal;
import static net.bytebuddy.matcher.ElementMatchers.isHashCode;
import static net.bytebuddy.matcher.ElementMatchers.isPackagePrivate;
import static net.bytebuddy.matcher.ElementMatchers.isToString;
import static net.bytebuddy.matcher.ElementMatchers.isVirtual;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.not;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
import static net.bytebuddy.matcher.ElementMatchers.takesNoArguments;
/**
* A class generator that uses <a href="https://bytebuddy.net/#/">Byte Buddy</a> to {@linkplain #generate(String,
* TypeDefinition, Collection) generate} {@linkplain org.microbean.proxy.Proxy client proxy} classes.
*
* @author <a href="https://about.me/lairdnelson" target="_top">Laird Nelson</a>
*/
public final class BBClientProxyClassGenerator {
private final TypePool typePool;
/**
* Creates a new {@link BBClientProxyClassGenerator}.
*
* @param typePool a non-{@code null} {@link TypePool} (normally a {@link TypeElementTypePool})
*
* @exception NullPointerException if {@code typePool} is {@code null}
*/
public BBClientProxyClassGenerator(final TypePool typePool) {
super();
this.typePool = requireNonNull(typePool, "typePool");
}
/**
* Creates and returns a new {@link DynamicType.Unloaded} representing a client proxy class.
*
* @param name the non-{@code null} name of the client proxy class; must be a valid Java class <a
* href="https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/lang/ClassLoader.html#binary-name">binary
* name</a>
*
* @param superclass a non-{@code null} {@link TypeDefinition} representing a superclass
*
* @param interfaces a non-{@code null} {@link Collection} of {@link TypeDefinition}s representing interfaces the
* client proxy class will implement
*
* @return a new, non-{@code null} {@link DynamicType.Unloaded} representing a client proxy class
*
* @exception NullPointerException if any argument is {@code null}
*/
public final DynamicType.Unloaded<?> generate(final String name,
final TypeDefinition superclass,
final Collection<? extends TypeDefinition> interfaces) {
// Proxy<Superclass>
final TypeDescription.Generic proxyType =
parameterizedType(this.typeDescription("org.microbean.proxy.Proxy"),
List.of(superclass))
.build();
// Supplier<? extends Superclass>
final TypeDescription.Generic supplierType =
parameterizedType(this.typeDescription("java.util.function.Supplier"),
List.of(TypeDescription.Generic.Builder.of(superclass.asGenericType()).asWildcardUpperBound()))
.build();
// public /* synthetic */ final class Name extends Superclass implements Proxy<Superclass>, Interfaces { /* ... */ }
DynamicType.Builder<?> builder = new ByteBuddy()
.subclass(superclass, NO_CONSTRUCTORS)
.merge(List.of(PUBLIC, SYNTHETIC, TypeManifestation.FINAL))
.name(name)
.implement(proxyType)
.implement(interfaces)
// private final Supplier<? extends Superclass> $proxiedSupplier;
.defineField("$proxiedSupplier", supplierType, PRIVATE, SYNTHETIC, FieldManifestation.FINAL)
// public Name(final Supplier<? extends Superclass> proxiedSupplier) {
// super();
// Objects.requireNonNull(proxiedSupplier, "proxiedSupplier");
// this.$proxiedSupplier = proxiedSupplier;
// }
.defineConstructor(PUBLIC, SYNTHETIC)
.withParameter(supplierType, "proxiedSupplier", ParameterManifestation.FINAL)
.intercept(invoke(superclass.getDeclaredMethods().filter(isConstructor().and(takesNoArguments())).getOnly())
.andThen(invoke(this.typeDescription("java.util.Objects")
.getDeclaredMethods()
.filter(named("requireNonNull")
.and(takesArgument(1, this.typeDescription("java.lang.String"))))
.getOnly())
.withArgument(0)
.with("proxiedSupplier"))
.andThen(FieldAccessor.ofField("$proxiedSupplier").setsArgumentAt(0)))
// @Override // Proxy<Superclass>
// public final Superclass $proxied() {
// return this.$proxiedSupplier.get();
// }
.defineMethod("$proxied", superclass, PUBLIC, SYNTHETIC, MethodManifestation.FINAL)
.intercept(invoke(named("get"))
.onField("$proxiedSupplier")
.withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC))
// @Override // Proxy<Superclass>
// public final Superclass $cast() {
// return Proxy.super.$cast();
// }
.defineMethod("$cast", superclass, PUBLIC, SYNTHETIC, MethodManifestation.FINAL)
.intercept(DefaultMethodCall.prioritize(proxyType.asErasure()))
// Existing/inherited methods; remember that they form a stack, so the last .method() call below should be the
// most specific. See https://bytebuddy.net/#members for details.
// @Override // Superclass/interfaces
// public Bar foo() {
// return $proxied().foo(); // so long as foo() meets certain requirements
// }
.method(isBusinessMethod()
.and(not(isJavaDeclaredMethod()
.and(isPackagePrivate()
.or(hasOneOrMorePackagePrivateParameters())))))
.intercept(invokeSelf()
.onMethodCall(invoke(named("$proxied")))
.withAllArguments())
// @Override // Superclass, Object
// public final boolean equals(final Object other) {
// if (other == this) {
// return true;
// } else if (other != null && other.getClass() == this.getClass()) {
// return this.$proxiedSupplier == ((Name)other).$proxiedSupplier;
// } else {
// return false;
// }
// }
.method(isEquals())
.intercept(EqualsMethod.isolated()
.withIdentityFields(any()) // there's only one
.withNonNullableFields(any()))
// @Override // Superclass, Object
// public int hashCode() {
// int offset = 31;
// return offset * 17 + this.$proxiedSupplier.hashCode(); // or similar
// }
.method(isHashCode())
.intercept(HashCodeMethod.usingOffset(31)
.withIdentityFields(any())
.withNonNullableFields(any())
.withMultiplier(17)) // see https://github.com/raphw/byte-buddy/issues/1764
// @Override // Superclass/interfaces/Object
// public String toString() {
// return $proxied().toString();
// }
.method(isToString())
.intercept(invoke(named("toString"))
.onMethodCall(invoke(named("$proxied"))));
return builder.make(this.typePool);
}
/*
* Static methods.
*/
private static final ElementMatcher<MethodDescription> hasOneOrMorePackagePrivateParameters() {
return m -> {
for (final ParameterDescription pd : m.getParameters()) {
if (isPackagePrivate().matches(pd.getType())) {
return true;
}
}
return false;
};
}
private static final ElementMatcher.Junction<MethodDescription> isBusinessMethod() {
return isVirtual()
.and(not(isFinal()))
.and(not(isDeclaredBy(Object.class)));
}
private static final ElementMatcher.Junction<MethodDescription> isJavaDeclaredMethod() {
return isDeclaredBy(t -> t.getTypeName().startsWith("java."));
}
private final TypeDescription typeDescription(final String canonicalName) {
return this.typePool.describe(canonicalName).resolve();
}
}