本文整理汇总了Java中net.bytebuddy.dynamic.DynamicType类的典型用法代码示例。如果您正苦于以下问题:Java DynamicType类的具体用法?Java DynamicType怎么用?Java DynamicType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DynamicType类属于net.bytebuddy.dynamic包,在下文中一共展示了DynamicType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: transform
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@Override
public DynamicType.Builder<?> transform(
final DynamicType.Builder<?> builder,
final TypeDescription typeDescription,
final ClassLoader classLoader,
final JavaModule module) {
final AsmVisitorWrapper methodsVisitor =
Advice.to(EnterAdvice.class, ExitAdviceMethods.class)
.on(ElementMatchers.isAnnotatedWith(CollectMetrics.class)
.and(ElementMatchers.isMethod()));
final AsmVisitorWrapper constructorsVisitor =
Advice.to(EnterAdvice.class, ExitAdviceConstructors.class)
.on(ElementMatchers.isAnnotatedWith(CollectMetrics.class)
.and(ElementMatchers.isConstructor()));
return builder.visit(methodsVisitor).visit(constructorsVisitor);
}
示例2: build
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
public static <T> Class<?> build(Class<T> origin, String name, MethodInclusion methodInclusion, Object interceptor) {
DynamicType.Builder<T> builder = new ByteBuddy()
.subclass(origin).name(proxyClassName(name));
Class<?> cachedClass = classCache.get(origin);
if (cachedClass != null) {
return cachedClass;
}
Class<? extends T> proxied = builder
.method(methodInclusion.getIncludes())
.intercept(MethodDelegation.to(interceptor))
.make()
.load(ProxyClassBuilder.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
classCache.putIfAbsent(origin, proxied);
return proxied;
}
示例3: buildApiListingEndpoint
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
/**
* Build a Swagger API listing JAX-RS endpoint class, binding it to given <code>path</code> using standard JAX-RS
* {@link Path} annotation.
* @param classLoader ClassLoader to use to create the class proxy
* @param apiGroupId API group id
* @param path Endpoint path
* @param authSchemes Authenticatiob schemes
* @param rolesAllowed Optional security roles for endpoint authorization
* @return The Swagger API listing JAX-RS endpoint class proxy
*/
public static Class<?> buildApiListingEndpoint(ClassLoader classLoader, String apiGroupId, String path,
String[] authSchemes, String[] rolesAllowed) {
String configId = (apiGroupId != null && !apiGroupId.trim().equals("")) ? apiGroupId
: ApiGroupId.DEFAULT_GROUP_ID;
final ClassLoader cl = (classLoader != null) ? classLoader : ClassUtils.getDefaultClassLoader();
DynamicType.Builder<SwaggerApiListingResource> builder = new ByteBuddy()
.subclass(SwaggerApiListingResource.class)
.annotateType(AnnotationDescription.Builder.ofType(Path.class).define("value", path).build())
.annotateType(AnnotationDescription.Builder.ofType(ApiGroupId.class).define("value", configId).build());
if (authSchemes != null && authSchemes.length > 0) {
if (authSchemes.length == 1 && authSchemes[0] != null && authSchemes[0].trim().equals("*")) {
builder = builder.annotateType(AnnotationDescription.Builder.ofType(Authenticate.class).build());
} else {
builder = builder.annotateType(AnnotationDescription.Builder.ofType(Authenticate.class)
.defineArray("schemes", authSchemes).build());
}
}
if (rolesAllowed != null && rolesAllowed.length > 0) {
builder = builder.annotateType(AnnotationDescription.Builder.ofType(RolesAllowed.class)
.defineArray("value", rolesAllowed).build());
}
return builder.make().load(cl, ClassLoadingStrategy.Default.INJECTION).getLoaded();
}
示例4: check
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@Override
public final void check() throws Exception {
final TypeDescription typeDescription = new TypeDescription.ForLoadedType(clazz);
final DynamicType.Builder<?> subclass = new ByteBuddy().redefine(clazz);
final DynamicType.Unloaded<?> make = bt
.transitionResult(subclass, typeDescription)
.value()
.get()
.make();
final Class<?> newClazz = make.load(new AnonymousClassLoader()).getLoaded();
assertThat(
List.of(newClazz.getDeclaredMethods()).map(Method::getName)
).containsOnlyElementsOf(
methodNames
);
}
开发者ID:project-avral,项目名称:oo-atom,代码行数:17,代码来源:AssertClassToHaveCertainMethodsAfterBuilderTransition.java
示例5: createMethodIdProxy
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
private static <C> C createMethodIdProxy(final Class<C> interfaceToProxy, final Optional<String> scopeNameOpt)
{
final List<ConfigDescriptor> configDescList = ConfigSystem.descriptorFactory.buildDescriptors(interfaceToProxy, scopeNameOpt);
DynamicType.Builder<C> typeBuilder = new ByteBuddy().subclass(interfaceToProxy);
for (ConfigDescriptor desc : configDescList) {
typeBuilder = typeBuilder.method(ElementMatchers.is(desc.getMethod())).intercept(InvocationHandlerAdapter.of((Object proxy, Method method1, Object[] args) -> {
log.trace("BB InvocationHandler identifying method {} proxy {}, argCount {}", method1.getName(), proxy.toString(), args.length);
lastIdentifiedMethodAndScope.set(new MethodAndScope(method1, scopeNameOpt));
return defaultForType(desc.getMethod().getReturnType());
}));
}
Class<? extends C> configImpl = typeBuilder.make()
.load(interfaceToProxy.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded();
try {
return configImpl.newInstance();
}
catch (InstantiationException | IllegalAccessException ex) {
throw new ConfigException("Failed to instantiate identification implementation of Config {} scope {}",
interfaceToProxy.getName(), scopeNameOpt.orElse("<empty>"), ex);
}
}
示例6: createInstanceWithFields
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
private Object createInstanceWithFields(Parameter[] parameters)
{
DynamicType.Builder<Object> objectBuilder = new ByteBuddy().subclass(Object.class)
.modifiers(PUBLIC);
for (Parameter parameter : parameters) {
objectBuilder = objectBuilder.defineField(parameter.getName(), parameter.getType(), PUBLIC)
.annotateField(ArrayUtils.add(parameter.getAnnotations(), INJECT_ANNOTATION));
}
try {
Class<?> createdClass = objectBuilder.make()
.load(getSystemClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded();
return createdClass
.getConstructor()
.newInstance();
}
catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
示例7: processMethod
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@Override
public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation) {
final java.lang.reflect.Parameter[] arguments = method.getParameters();
if (ReflectionUtility.isSetMethod(method))
if (arguments == null || arguments.length == 0)
throw new IllegalStateException(method.getName() + " was annotated with @Property but had no arguments.");
else if (arguments.length == 1)
return this.setProperty(builder, method, annotation);
else
throw new IllegalStateException(method.getName() + " was annotated with @Property but had more than 1 arguments.");
else if (ReflectionUtility.isGetMethod(method))
if (arguments == null || arguments.length == 0)
return this.getProperty(builder, method, annotation);
else
throw new IllegalStateException(method.getName() + " was annotated with @Property but had arguments.");
else if (ReflectionUtility.isRemoveMethod(method))
if (arguments == null || arguments.length == 0)
return this.removeProperty(builder, method, annotation);
else
throw new IllegalStateException(method.getName() + " was annotated with @Property but had some arguments.");
else
throw new IllegalStateException(method.getName() + " was annotated with @Property but did not begin with either of the following keywords: add, get");
}
示例8: testCustomHandlers
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@Test
public void testCustomHandlers() {
MethodHandler custom = Mockito.mock(AbstractMethodHandler.class, Mockito.CALLS_REAL_METHODS);
Class<? extends Annotation> annotation = Adjacency.class;
custom = Mockito.when(custom.getAnnotationType()).then(inv -> annotation).getMock();
custom = Mockito
.when(custom.processMethod(Mockito.any(), Mockito.any(), Mockito.any()))
.thenAnswer(inv -> inv.getArgumentAt(0, DynamicType.Builder.class))
.getMock();
AbstractAnnotationFrameFactory frameFactory = new AbstractAnnotationFrameFactory(new ReflectionCache(), Collections.singleton(custom)) {
};
DelegatingFramedGraph framedGraph = new DelegatingFramedGraph(fg.getBaseGraph(), frameFactory, new PolymorphicTypeResolver());
framedGraph.addFramedVertex(God.class);
Mockito.verify(custom, Mockito.atLeast(0)).getAnnotationType();
Mockito.verify(custom, Mockito.atLeastOnce()).processMethod(Mockito.any(), Mockito.any(), Mockito.any());
}
示例9: testRetrieveFromArray
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@Test
public void testRetrieveFromArray() throws Exception {
DynamicType.Unloaded<RetrieveFromArray> arr = new ByteBuddy().subclass(RetrieveFromArray.class)
.method(ElementMatchers.isDeclaredBy(RetrieveFromArray.class))
.intercept(new Implementation.Compound(new LoadReferenceParamImplementation(1),
new RelativeRetrieveArrayImplementation(1),
new ReturnAppenderImplementation(ReturnAppender.ReturnType.INT)))
.make();
Class<?> dynamicType = arr.load(RetrieveFromArray.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
RetrieveFromArray test = (RetrieveFromArray) dynamicType.newInstance();
int result = test.returnVal(0, 1);
assertEquals(1, result);
}
示例10: inPlaceSet
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@Test
public void inPlaceSet() throws Exception {
DynamicType.Unloaded<SetValueInPlace> val =
new ByteBuddy().subclass(SetValueInPlace.class)
.method(ElementMatchers.isDeclaredBy(SetValueInPlace.class))
.intercept(new StackManipulationImplementation(new StackManipulation.Compound(
MethodVariableAccess.REFERENCE.loadOffset(1),
MethodVariableAccess.INTEGER.loadOffset(2),
MethodVariableAccess.INTEGER.loadOffset(3),
ArrayStackManipulation.store(), MethodReturn.VOID)))
.make();
val.saveIn(new File("target"));
SetValueInPlace dv = val.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded()
.newInstance();
int[] ret = {2, 4};
int[] assertion = {1, 4};
dv.update(ret, 0, 1);
assertArrayEquals(assertion, ret);
}
示例11: inPlaceDivide
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@Test
public void inPlaceDivide() throws Exception {
DynamicType.Unloaded<SetValueInPlace> val = new ByteBuddy().subclass(SetValueInPlace.class)
.method(ElementMatchers.isDeclaredBy(SetValueInPlace.class))
.intercept(new StackManipulationImplementation(new StackManipulation.Compound(
MethodVariableAccess.REFERENCE.loadOffset(1),
MethodVariableAccess.INTEGER.loadOffset(2), Duplication.DOUBLE,
ArrayStackManipulation.load(), MethodVariableAccess.INTEGER.loadOffset(3),
OpStackManipulation.div(), ArrayStackManipulation.store(), MethodReturn.VOID)))
.make();
val.saveIn(new File("target"));
SetValueInPlace dv = val.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded()
.newInstance();
int[] ret = {2, 4};
int[] assertion = {1, 4};
dv.update(ret, 0, 2);
assertArrayEquals(assertion, ret);
}
示例12: testCreateAndAssign
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@Test
public void testCreateAndAssign() throws Exception {
DynamicType.Unloaded<CreateAndAssignArray> arr = new ByteBuddy().subclass(CreateAndAssignArray.class)
.method(ElementMatchers.isDeclaredBy(CreateAndAssignArray.class))
.intercept(new Implementation.Compound(new IntArrayCreation(5), new DuplicateImplementation(),
new RelativeArrayAssignWithValueImplementation(0, 5),
new ReturnAppenderImplementation(ReturnAppender.ReturnType.REFERENCE)))
.make();
Class<?> dynamicType =
arr.load(CreateAndAssignArray.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
CreateAndAssignArray test = (CreateAndAssignArray) dynamicType.newInstance();
int[] result = test.create();
assertEquals(5, result[0]);
}
示例13: testCreateInt
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@Test
public void testCreateInt() throws Exception {
DynamicType.Unloaded<CreateAndAssignIntArray> arr = new ByteBuddy().subclass(CreateAndAssignIntArray.class)
.method(ElementMatchers.isDeclaredBy(CreateAndAssignIntArray.class))
.intercept(new Implementation.Compound(new ConstantIntImplementation(1),
new StoreIntImplementation(0), new LoadIntegerImplementation(0),
new ReturnAppenderImplementation(ReturnAppender.ReturnType.INT)))
.make();
Class<?> dynamicType =
arr.load(CreateAndAssignIntArray.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
CreateAndAssignIntArray test = (CreateAndAssignIntArray) dynamicType.newInstance();
int result = test.returnVal();
assertEquals(1, result);
}
示例14: testSetter
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private <Z extends CallTraceable> void testSetter(Class<Z> target, Implementation implementation) throws Exception {
DynamicType.Loaded<Z> loaded = new ByteBuddy()
.subclass(target)
.method(isDeclaredBy(target))
.intercept(implementation)
.make()
.load(target.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
Z instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(target)));
assertThat(instance, instanceOf(target));
Method setter = loaded.getLoaded()
.getDeclaredMethod(SET + Character.toUpperCase(FOO.charAt(0)) + FOO.substring(1), propertyType);
assertThat(setter.invoke(instance, value), nullValue());
instance.assertZeroCalls();
assertFieldValue(target, instance);
}
示例15: testStaticAdapterWithMethodCache
import net.bytebuddy.dynamic.DynamicType; //导入依赖的package包/类
@Test
public void testStaticAdapterWithMethodCache() throws Exception {
Foo foo = new Foo();
DynamicType.Loaded<Bar> loaded = new ByteBuddy()
.subclass(Bar.class)
.method(isDeclaredBy(Bar.class))
.intercept(InvocationHandlerAdapter.of(foo))
.make()
.load(Bar.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(2));
Bar instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
assertThat(instance.bar(FOO), is((Object) instance));
assertThat(foo.methods.size(), is(1));
assertThat(instance.bar(FOO), is((Object) instance));
assertThat(foo.methods.size(), is(2));
assertThat(foo.methods.get(0), sameInstance(foo.methods.get(1)));
instance.assertZeroCalls();
}