当前位置: 首页>>代码示例>>Java>>正文


Java ByteBuddy类代码示例

本文整理汇总了Java中net.bytebuddy.ByteBuddy的典型用法代码示例。如果您正苦于以下问题:Java ByteBuddy类的具体用法?Java ByteBuddy怎么用?Java ByteBuddy使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ByteBuddy类属于net.bytebuddy包,在下文中一共展示了ByteBuddy类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testRedefinitionReloadingStrategy

import net.bytebuddy.ByteBuddy; //导入依赖的package包/类
@Test
@AgentAttachmentRule.Enforce(redefinesClasses = true)
public void testRedefinitionReloadingStrategy() throws Exception {
    assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
    Foo foo = new Foo();
    assertThat(foo.foo(), is(FOO));
    ClassReloadingStrategy classReloadingStrategy = new ClassReloadingStrategy(ByteBuddyAgent.getInstrumentation(), ClassReloadingStrategy.Strategy.REDEFINITION);
    new ByteBuddy()
            .redefine(Foo.class)
            .method(named(FOO))
            .intercept(FixedValue.value(BAR))
            .make()
            .load(Foo.class.getClassLoader(), classReloadingStrategy);
    try {
        assertThat(foo.foo(), is(BAR));
    } finally {
        classReloadingStrategy.reset(Foo.class);
        assertThat(foo.foo(), is(FOO));
    }
}
 
开发者ID:raphw,项目名称:byte-buddy,代码行数:21,代码来源:ClassReloadingStrategyTest.java

示例2: createProxy

import net.bytebuddy.ByteBuddy; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private T createProxy(
        final Class<T> clazz,
        final InterceptorChain chain
) {
    this.chain = chain;
    try {
        final InvocationHandler invocationHandler = (proxy, method, args) ->
                invokeIntercepted(args, instance(), method, AROUND_INVOKE);
        final Class<? extends T> dynamicType = new ByteBuddy()
                .subclass(clazz)
                .method(any()).intercept(InvocationHandlerAdapter.of(invocationHandler))
                .make()
                .load(getClass().getClassLoader())
                .getLoaded();
        return (T) dynamicType.newInstance();
    } catch (final IllegalAccessException | InstantiationException e) {
        throw new TestEEfiException("Failed to create proxy instance of " + clazz, e);
    }
}
 
开发者ID:dajudge,项目名称:testee.fi,代码行数:21,代码来源:SingletonHolder.java

示例3: build

import net.bytebuddy.ByteBuddy; //导入依赖的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;
}
 
开发者ID:YanXs,项目名称:nighthawk,代码行数:17,代码来源:ProxyClassBuilder.java

示例4: buildApiListingEndpoint

import net.bytebuddy.ByteBuddy; //导入依赖的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();
}
 
开发者ID:holon-platform,项目名称:holon-jaxrs,代码行数:34,代码来源:SwaggerJaxrsUtils.java

示例5: check

import net.bytebuddy.ByteBuddy; //导入依赖的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

示例6: createAgentBuilder

import net.bytebuddy.ByteBuddy; //导入依赖的package包/类
/**
 * Creates the AgentBuilder that will redefine the System class.
 * @param inst instrumentation instance.
 * @return an agent builder.
 */
private static AgentBuilder createAgentBuilder(Instrumentation inst) {

    // Find me a class called "java.lang.System"
    final ElementMatcher.Junction<NamedElement> systemType = ElementMatchers.named("java.lang.System");

    // And then find a method called setSecurityManager and tell MySystemInterceptor to
    // intercept it (the method binding is smart enough to take it from there)
    final AgentBuilder.Transformer transformer =
            (b, typeDescription) -> b.method(ElementMatchers.named("setSecurityManager"))
                    .intercept(MethodDelegation.to(MySystemInterceptor.class));

    // Disable a bunch of stuff and turn on redefine as the only option
    final ByteBuddy byteBuddy = new ByteBuddy().with(Implementation.Context.Disabled.Factory.INSTANCE);
    final AgentBuilder agentBuilder = new AgentBuilder.Default()
            .withByteBuddy(byteBuddy)
            .withInitializationStrategy(AgentBuilder.InitializationStrategy.NoOp.INSTANCE)
            .withRedefinitionStrategy(AgentBuilder.RedefinitionStrategy.REDEFINITION)
            .withTypeStrategy(AgentBuilder.TypeStrategy.Default.REDEFINE)
            .type(systemType)
            .transform(transformer);

    return agentBuilder;
}
 
开发者ID:wsargent,项目名称:securityfixer,代码行数:29,代码来源:SecurityFixerAgent.java

示例7: createMethodIdProxy

import net.bytebuddy.ByteBuddy; //导入依赖的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);
    }
}
 
开发者ID:kikinteractive,项目名称:ice,代码行数:25,代码来源:MethodIdProxyFactory.java

示例8: bingoo

import net.bytebuddy.ByteBuddy; //导入依赖的package包/类
public void bingoo() throws IllegalAccessException, InstantiationException {
    Class<? extends BingooVisitor> dynamicType = new ByteBuddy()
            .subclass(BingooVisitor.class)
            .method(any())
            .intercept(MethodDelegation.to(new GeneralInterceptor()))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();

    BingooVisitor bingooVisitor = dynamicType.newInstance();
    System.out.println(dynamicType.getName());
    String s = bingooVisitor.sayHello();
    System.out.println(s);
    System.out.println(bingooVisitor.sayWorld());

}
 
开发者ID:bingoohuang,项目名称:javacode-demo,代码行数:17,代码来源:ByteBuddyDemo.java

示例9: generateQueryResultClass

import net.bytebuddy.ByteBuddy; //导入依赖的package包/类
/**
 * Generates enhanced subclass of query result class. The enhanced subclass
 * does have a constructor for initializing all mapped fields.
 * 
 * @return the generated subclass
 */
private Class<?> generateQueryResultClass() {
	LOGGER.debug("Mapped fields of result: {}", mappedFields);
	Class<?>[] fieldTypes = mappedFields.stream().map(f -> f.getType()).collect(Collectors.toList())
			.toArray(new Class<?>[] {});

	Unloaded<T> unloadedSubClass;
	try {
		unloadedSubClass = new ByteBuddy().with(new NamingStrategy.SuffixingRandom("Query")).subclass(resultClazz)
				.defineConstructor(MethodArguments.VARARGS, Visibility.PUBLIC).withParameters(fieldTypes)
				.intercept(MethodCall.invoke(this.resultClazz.getDeclaredConstructor())
						.andThen(MethodDelegation.to(new ConstructorInitializer(mappedFields))))
				.make();
	} catch (NoSuchMethodException | SecurityException e) {
		throw new RuntimeException("Generation of subclass for " + resultClazz.getName() + " failed", e);
	}

	return unloadedSubClass
			.load(Thread.currentThread().getContextClassLoader(), ClassLoadingStrategy.Default.INJECTION)
			.getLoaded();
}
 
开发者ID:bbvch,项目名称:JpqlQueryBuilder,代码行数:27,代码来源:QueryResultEnhancer.java

示例10: transform

import net.bytebuddy.ByteBuddy; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Nullable
public static <T extends Annotation> Class<? extends T> transform(Class<T> clazz)
{
    if (! clazz.isAnnotation() || ! (clazz.isAnnotationPresent(Qualifier.class) || clazz.isAnnotationPresent(Scope.class)))
    {
        return null;
    }
    try
    {
        String name = GENERATED_PREFIX + "." + clazz.getName();
        Unloaded<Object> make = new ByteBuddy(ClassFileVersion.JAVA_V9).subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
                                                                       .implement(Serializable.class, clazz).name(name)
                                                                       .visit(new AnnotationImplementationVisitor(new ForLoadedType(clazz))).make();
        Loaded<Object> load = make.load(ClassLoader.getSystemClassLoader(), Default.INJECTION);
        return (Class<? extends T>) load.getLoaded();
    }
    catch (Throwable e)
    {
        throw new RuntimeException(e);
    }
}
 
开发者ID:Diorite,项目名称:Diorite,代码行数:23,代码来源:QualifierAndScopeImplementationGenerator.java

示例11: giveDynamicSubclass

import net.bytebuddy.ByteBuddy; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private static synchronized <S> Class<S> giveDynamicSubclass(Class<S> superclass) {
    boolean isSystemClass = isSystemClass(superclass.getName());
    String namePrefix = isSystemClass ? "$" : "";
    String name = namePrefix + superclass.getName() + "$$DynamicSubclass";

    Class<S> existsAlready = (Class<S>)classForName(name);
    if (existsAlready != null) {
        return existsAlready;
    }

    Class<?> context = isSystemClass ? Instantiator.class : superclass;
    return (Class<S>)new ByteBuddy()
            .with(TypeValidation.DISABLED)
            .subclass(superclass)
            .name(name)
            .make()
            .load(context.getClassLoader(), ClassLoadingStrategy.Default.INJECTION.with(context.getProtectionDomain()))
            .getLoaded();
}
 
开发者ID:jqno,项目名称:equalsverifier,代码行数:21,代码来源:Instantiator.java

示例12: install

import net.bytebuddy.ByteBuddy; //导入依赖的package包/类
public static void install() {
    ByteBuddyAgent.install();

    ClassLoader targetClassLoader = File.class.getClassLoader();

    // interceptor class must be injected to the same classloader as the target class that is intercepted
    new ByteBuddy().redefine(CountFileSystemOperations.class)
            .make()
            .load(targetClassLoader,
                    ClassReloadingStrategy.fromInstalledAgent());

    new ByteBuddy().redefine(DirectoryFileTree.class)
            .visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES)
                    .method(ElementMatchers.named("length"), Advice.to(CountFileSystemOperations.LengthMethod.class))
                    .method(ElementMatchers.named("isFile"), Advice.to(CountFileSystemOperations.IsFileMethod.class))
                    .method(ElementMatchers.named("isDirectory"), Advice.to(CountFileSystemOperations.IsDirectoryMethod.class))
                    .method(ElementMatchers.named("lastModified"), Advice.to(CountFileSystemOperations.LastModifiedMethod.class))
                    .method(ElementMatchers.named("exists"), Advice.to(CountFileSystemOperations.ExistsMethod.class))

            )
            .make()
            .load(targetClassLoader,
                    ClassReloadingStrategy.fromInstalledAgent());
}
 
开发者ID:lhotari,项目名称:gradle-profiling,代码行数:25,代码来源:FileSystemOperationsInterceptor.java

示例13: install

import net.bytebuddy.ByteBuddy; //导入依赖的package包/类
public static void install() {
    ByteBuddyAgent.install();

    ClassLoader targetClassLoader = DirectoryFileTree.class.getClassLoader();

    // interceptor class must be injected to the same classloader as the target class that is intercepted
    new ByteBuddy().redefine(CountDirectoryScans.class)
            .make()
            .load(targetClassLoader,
                    ClassReloadingStrategy.fromInstalledAgent());

    new ByteBuddy().redefine(DirectoryFileTree.class)
            .visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES).method(ElementMatchers.named("visitFrom"), Advice.to(CountDirectoryScans.class)))
            .make()
            .load(targetClassLoader,
                    ClassReloadingStrategy.fromInstalledAgent());
}
 
开发者ID:lhotari,项目名称:gradle-profiling,代码行数:18,代码来源:DirectoryScanningInterceptor.java

示例14: createInstanceWithFields

import net.bytebuddy.ByteBuddy; //导入依赖的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);
    }
}
 
开发者ID:prestodb,项目名称:tempto,代码行数:21,代码来源:ReflectionInjectorHelper.java

示例15: createConverterClass

import net.bytebuddy.ByteBuddy; //导入依赖的package包/类
private void createConverterClass(Converter convert, ClassLoader classLoader) {
        //create Java Class
        Class<?> attributeConverter = new ByteBuddy()
//                .subclass(TypeDescription.Generic.Builder.parameterizedType(AttributeConverter.class, String.class, Integer.class).build())
                .subclass(AttributeConverter.class)
                .name(convert.getClazz())
                .annotateType(AnnotationDescription.Builder.ofType(javax.persistence.Converter.class).build())
                .make()
                .load(classLoader, ClassLoadingStrategy.Default.INJECTION)
                .getLoaded();

        //create MetadataClass
        MetadataClass metadataClass = new MetadataClass(getMetadataFactory(), convert.getClazz());
        metadataClass.addInterface(AttributeConverter.class.getName());
        metadataClass.addGenericType("");
        metadataClass.addGenericType("");
        metadataClass.addGenericType(convert.getAttributeType());
        metadataClass.addGenericType("");
        metadataClass.addGenericType(convert.getFieldType());
        getMetadataFactory().addMetadataClass(metadataClass);

    }
 
开发者ID:jeddict,项目名称:jeddict,代码行数:23,代码来源:DBEntityMappings.java


注:本文中的net.bytebuddy.ByteBuddy类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。