Java Code Examples for net.bytebuddy.dynamic.DynamicType#Unloaded

The following examples show how to use net.bytebuddy.dynamic.DynamicType#Unloaded . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ByteBuddyProcessFunctionInvoker.java    From da-streamingledger with Apache License 2.0 6 votes vote down vote up
private static <InT, OutT> DynamicType.Unloaded<?> createDynamicTypeFromSpec(StreamingLedgerSpec<InT, OutT> spec)
        throws NoSuchMethodException {
    PackageLocalNamingStrategy generatedTypeName = new PackageLocalNamingStrategy(spec.processFunction.getClass());

    TypeDefinition generatedType = Generic.Builder.parameterizedType(
            ProcessFunctionInvoker.class,
            spec.inputType.getTypeClass(),
            spec.resultType.getTypeClass()
    ).build();

    TypeDefinition processFunctionType = new TypeDescription.ForLoadedType(spec.processFunction.getClass());
    ForLoadedConstructor superTypeConstructor =
            new ForLoadedConstructor(ProcessFunctionInvoker.class.getDeclaredConstructor());
    MethodDescription processMethodType = processMethodTypeFromSpec(spec);

    Builder<?> builder = configureByteBuddyBuilder(
            generatedTypeName,
            generatedType,
            processFunctionType,
            superTypeConstructor,
            processMethodType,
            spec.stateBindings.size());

    return builder.make();
}
 
Example 2
Source File: BootstrapInstrumentBoost.java    From skywalking with Apache License 2.0 6 votes vote down vote up
/**
 * Generate the delegator class based on given template class. This is preparation stage level code generation.
 * <p>
 * One key step to avoid class confliction between AppClassLoader and BootstrapClassLoader
 *
 * @param classesTypeMap    hosts injected binary of generated class
 * @param typePool          to generate new class
 * @param templateClassName represents the class as template in this generation process. The templates are
 *                          pre-defined in SkyWalking agent core.
 */
private static void generateDelegator(Map<String, byte[]> classesTypeMap, TypePool typePool,
    String templateClassName, String methodsInterceptor) {
    String internalInterceptorName = internalDelegate(methodsInterceptor);
    try {
        TypeDescription templateTypeDescription = typePool.describe(templateClassName).resolve();

        DynamicType.Unloaded interceptorType = new ByteBuddy().redefine(templateTypeDescription, ClassFileLocator.ForClassLoader
            .of(BootstrapInstrumentBoost.class.getClassLoader()))
                                                              .name(internalInterceptorName)
                                                              .field(named("TARGET_INTERCEPTOR"))
                                                              .value(methodsInterceptor)
                                                              .make();

        classesTypeMap.put(internalInterceptorName, interceptorType.getBytes());

        InstrumentDebuggingClass.INSTANCE.log(interceptorType);
    } catch (Exception e) {
        throw new PluginException("Generate Dynamic plugin failure", e);
    }
}
 
Example 3
Source File: SubclassDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType.Unloaded<T> make(TypeResolutionStrategy typeResolutionStrategy, TypePool typePool) {
    MethodRegistry.Compiled methodRegistry = constructorStrategy
            .inject(instrumentedType, this.methodRegistry)
            .prepare(applyConstructorStrategy(instrumentedType),
                methodGraphCompiler,
                typeValidation,
                visibilityBridgeStrategy,
                new InstrumentableMatcher(ignoredMethods))
            .compile(SubclassImplementationTarget.Factory.SUPER_CLASS, classFileVersion);
    return TypeWriter.Default.<T>forCreation(methodRegistry,
            auxiliaryTypes,
            fieldRegistry.compile(methodRegistry.getInstrumentedType()),
            recordComponentRegistry.compile(methodRegistry.getInstrumentedType()),
            typeAttributeAppender,
            asmVisitorWrapper,
            classFileVersion,
            annotationValueFilterFactory,
            annotationRetention,
            auxiliaryTypeNamingStrategy,
            implementationContextFactory,
            typeValidation,
            classWriterStrategy,
            typePool).make(typeResolutionStrategy.resolve());
}
 
Example 4
Source File: DecoratingDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType.Unloaded<T> make(TypeResolutionStrategy typeResolutionStrategy, TypePool typePool) {
    return TypeWriter.Default.<T>forDecoration(instrumentedType,
            classFileVersion,
            auxiliaryTypes,
            CompoundList.of(methodGraphCompiler.compile(instrumentedType)
                    .listNodes()
                    .asMethodList()
                    .filter(not(ignoredMethods.resolve(instrumentedType))), instrumentedType.getDeclaredMethods().filter(not(isVirtual()))),
            typeAttributeAppender,
            asmVisitorWrapper,
            annotationValueFilterFactory,
            annotationRetention,
            auxiliaryTypeNamingStrategy,
            implementationContextFactory,
            typeValidation,
            classWriterStrategy,
            typePool,
            classFileLocator).make(typeResolutionStrategy.resolve());
}
 
Example 5
Source File: RedefinitionDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType.Unloaded<T> make(TypeResolutionStrategy typeResolutionStrategy, TypePool typePool) {
    MethodRegistry.Prepared methodRegistry = this.methodRegistry.prepare(instrumentedType,
            methodGraphCompiler,
            typeValidation,
            visibilityBridgeStrategy,
            InliningImplementationMatcher.of(ignoredMethods, originalType));
    return TypeWriter.Default.<T>forRedefinition(methodRegistry,
            auxiliaryTypes,
            fieldRegistry.compile(methodRegistry.getInstrumentedType()),
            recordComponentRegistry.compile(methodRegistry.getInstrumentedType()),
            typeAttributeAppender,
            asmVisitorWrapper,
            classFileVersion,
            annotationValueFilterFactory,
            annotationRetention,
            auxiliaryTypeNamingStrategy,
            implementationContextFactory,
            typeValidation,
            classWriterStrategy,
            typePool,
            originalType,
            classFileLocator).make(typeResolutionStrategy.resolve());
}
 
Example 6
Source File: GenericSignatureResolutionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeVariableInterfaceBound() throws Exception {
    DynamicType.Unloaded<?> unloaded = new ByteBuddy()
            .redefine(TypeVariableInterfaceBound.class)
            .make();
    Class<?> type = unloaded.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    TypeDescription createdType = TypeDescription.ForLoadedType.of(type);
    TypeDescription originalType = TypeDescription.ForLoadedType.of(TypeVariableInterfaceBound.class);
    assertThat(createdType.getTypeVariables(), is(originalType.getTypeVariables()));
    assertThat(createdType.getSuperClass(), is(originalType.getSuperClass()));
    assertThat(createdType.getInterfaces(), is(originalType.getInterfaces()));
}
 
Example 7
Source File: GenericSignatureResolutionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeVariableWildcardLowerInterfaceBound() throws Exception {
    DynamicType.Unloaded<?> unloaded = new ByteBuddy()
            .redefine(TypeVariableWildcardLowerInterfaceBound.class)
            .make();
    Class<?> type = unloaded.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    TypeDescription createdType = TypeDescription.ForLoadedType.of(type);
    TypeDescription originalType = TypeDescription.ForLoadedType.of(TypeVariableWildcardLowerInterfaceBound.class);
    assertThat(createdType.getTypeVariables(), is(originalType.getTypeVariables()));
    assertThat(createdType.getSuperClass(), is(originalType.getSuperClass()));
    assertThat(createdType.getInterfaces(), is(originalType.getInterfaces()));
}
 
Example 8
Source File: GenericSignatureResolutionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeVariableWildcardUpperInterfaceBound() throws Exception {
    DynamicType.Unloaded<?> unloaded = new ByteBuddy()
            .redefine(TypeVariableWildcardUpperInterfaceBound.class)
            .make();
    Class<?> type = unloaded.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    TypeDescription createdType = TypeDescription.ForLoadedType.of(type);
    TypeDescription originalType = TypeDescription.ForLoadedType.of(TypeVariableWildcardUpperInterfaceBound.class);
    assertThat(createdType.getTypeVariables(), is(originalType.getTypeVariables()));
    assertThat(createdType.getSuperClass(), is(originalType.getSuperClass()));
    assertThat(createdType.getInterfaces(), is(originalType.getInterfaces()));
}
 
Example 9
Source File: GenericSignatureResolutionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeVariableWildcardLowerClassBound() throws Exception {
    DynamicType.Unloaded<?> unloaded = new ByteBuddy()
            .redefine(TypeVariableWildcardLowerClassBound.class)
            .make();
    Class<?> type = unloaded.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    TypeDescription createdType = TypeDescription.ForLoadedType.of(type);
    TypeDescription originalType = TypeDescription.ForLoadedType.of(TypeVariableWildcardLowerClassBound.class);
    assertThat(createdType.getTypeVariables(), is(originalType.getTypeVariables()));
    assertThat(createdType.getSuperClass(), is(originalType.getSuperClass()));
    assertThat(createdType.getInterfaces(), is(originalType.getInterfaces()));
}
 
Example 10
Source File: RebaseDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodRebase() throws Exception {
    DynamicType.Unloaded<?> dynamicType = new ByteBuddy()
            .rebase(Qux.class)
            .method(named(BAR)).intercept(StubMethod.INSTANCE)
            .make();
    assertThat(dynamicType.getAuxiliaryTypes().size(), is(0));
    Class<?> type = dynamicType.load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    assertThat(type.getDeclaredConstructors().length, is(1));
    assertThat(type.getDeclaredMethods().length, is(3));
    assertThat(type.getDeclaredMethod(FOO).invoke(null), nullValue(Object.class));
    assertThat(type.getDeclaredField(FOO).get(null), is((Object) FOO));
    assertThat(type.getDeclaredMethod(BAR).invoke(null), nullValue(Object.class));
    assertThat(type.getDeclaredField(FOO).get(null), is((Object) FOO));
}
 
Example 11
Source File: ByteBuddyTutorialExamplesTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testTutorialGettingStartedNamingStrategy() throws Exception {
    DynamicType.Unloaded<?> dynamicType = new ByteBuddy()
            .with(new GettingStartedNamingStrategy())
            .subclass(Object.class)
            .make();
    assertThat(dynamicType, notNullValue());
    Class<?> type = dynamicType.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    assertThat(type.getName(), is("i.love.ByteBuddy.Object"));
}
 
Example 12
Source File: ByteBuddyTutorialExamplesTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testTutorialGettingStartedNamed() throws Exception {
    DynamicType.Unloaded<?> dynamicType = new ByteBuddy()
            .subclass(Object.class)
            .name("example.Type")
            .make();
    assertThat(dynamicType, notNullValue());
}
 
Example 13
Source File: ByteBuddyUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException {
    DynamicType.Unloaded unloadedType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.isToString()).intercept(FixedValue.value("Hello World ByteBuddy!")).make();

    Class<?> dynamicType = unloadedType.load(getClass().getClassLoader()).getLoaded();

    assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!");
}
 
Example 14
Source File: GenericSignatureResolutionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeVariableWildcardUpperClassBound() throws Exception {
    DynamicType.Unloaded<?> unloaded = new ByteBuddy()
            .redefine(TypeVariableWildcardUpperClassBound.class)
            .make();
    Class<?> type = unloaded.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    TypeDescription createdType = TypeDescription.ForLoadedType.of(type);
    TypeDescription originalType = TypeDescription.ForLoadedType.of(TypeVariableWildcardUpperClassBound.class);
    assertThat(createdType.getTypeVariables(), is(originalType.getTypeVariables()));
    assertThat(createdType.getSuperClass(), is(originalType.getSuperClass()));
    assertThat(createdType.getInterfaces(), is(originalType.getInterfaces()));
}
 
Example 15
Source File: RedefinitionDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodRebase() throws Exception {
    DynamicType.Unloaded<?> dynamicType = new ByteBuddy()
            .redefine(Qux.class)
            .method(named(BAR)).intercept(StubMethod.INSTANCE)
            .make();
    assertThat(dynamicType.getAuxiliaryTypes().size(), is(0));
    Class<?> type = dynamicType.load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    assertThat(type.getDeclaredConstructors().length, is(1));
    assertThat(type.getDeclaredMethods().length, is(2));
    assertThat(type.getDeclaredMethod(FOO).invoke(null), nullValue(Object.class));
    assertThat(type.getDeclaredField(FOO).get(null), is((Object) FOO));
    assertThat(type.getDeclaredMethod(BAR).invoke(null), nullValue(Object.class));
    assertThat(type.getDeclaredField(FOO).get(null), is((Object) FOO));
}
 
Example 16
Source File: ValidateAvroSchema.java    From arvo2parquet with MIT License 5 votes vote down vote up
public static void bytecodePatchAvroSchemaClass(final File avroSchemaClassesDir) throws ClassNotFoundException, IOException {
  final String avroSchemaClassPackageName = "org.apache.avro";
  final String avroSchemaFullClassName = avroSchemaClassPackageName + ".Schema";
  final String relativeFilePath = getClassRelativeFilePath(avroSchemaClassPackageName, avroSchemaFullClassName);
  final File clsFile = new File(avroSchemaClassesDir, relativeFilePath);
  Files.deleteIfExists(clsFile.toPath());
  final Class<?>[] methArgTypesMatch = { String.class };
  final DynamicType.Unloaded<?> avroSchemaClsUnloaded = new ByteBuddy()
          .rebase(Class.forName(avroSchemaFullClassName))
          .method(named("validateName").and(returns(String.class)).and(takesArguments(methArgTypesMatch))
                  .and(isPrivate()).and(isStatic()))
          .intercept(MethodDelegation.to(AvroSchemaInterceptor.class))
          .make();
  avroSchemaClsUnloaded.saveIn(avroSchemaClassesDir);
}
 
Example 17
Source File: AbstractInliningDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType.Unloaded<T> make(TypeResolutionStrategy typeResolutionStrategy) {
    return make(typeResolutionStrategy, TypePool.Default.of(classFileLocator));
}
 
Example 18
Source File: AbstractAnnotationFrameFactory.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
private <E> Class<? extends E> constructClass(final Element element, final Class<E> clazz)
{
    Class constructedClass = constructedClassCache.get(clazz);
    if (constructedClass != null)
        return constructedClass;

    DynamicType.Builder<? extends E> classBuilder;
    if (clazz.isInterface())
    {
        if (element instanceof Vertex)
            classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().subclass(AbstractVertexFrame.class);
        else if (element instanceof Edge)
            classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().subclass(AbstractEdgeFrame.class);
        else
            throw new IllegalStateException("class is neither an Edge or a vertex!");

        if (clazz.getCanonicalName().contains("ByteBuddy"))
        {
            // if the input class is itself a bytebuddy class, only take its interfaces
            classBuilder = classBuilder.implement(clazz.getInterfaces());
        }
        else
        {
            classBuilder = classBuilder.implement(clazz);
        }
    }
    else
    {
        if (!(element instanceof Vertex || element instanceof Edge))
            throw new IllegalStateException("element is neither an edge nor a vertex");
        else if (element instanceof Vertex && !VertexFrame.class.isAssignableFrom(clazz))
            throw new IllegalStateException(clazz.getName() + " Class is not a type of VertexFrame");
        else if (element instanceof Edge && !EdgeFrame.class.isAssignableFrom(clazz))
            throw new IllegalStateException(clazz.getName() + " Class is not a type of EdgeFrame");
        classBuilder = new ByteBuddy().subclass(clazz);
    }

    classBuilder = classBuilder.defineField("reflectionCache", ReflectionCache.class, Visibility.PRIVATE, FieldManifestation.PLAIN)
                .implement(CachesReflection.class).intercept(FieldAccessor.ofBeanProperty());

    /*
     * Just a hack so that our generified frame types can work.
     *
     * This information will not really be used by the generated class.
     */
    classBuilder = classBuilder.typeVariable("T");

    // try and construct any abstract methods that are left
    for (final Method method : clazz.getMethods())
        if (isAbstract(method))
            annotation_loop: for (final Annotation annotation : method.getAnnotations())
            {
                final MethodHandler handler = methodHandlers.get(annotation.annotationType());
                if (handler != null)
                {
                    classBuilder = handler.processMethod(classBuilder, method, annotation);
                    break;
                }
            }

    DynamicType.Unloaded unloadedClass = classBuilder.make();
    constructedClass = unloadedClass.load(this.classLoader, ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    this.constructedClassCache.put(clazz, constructedClass);
    return constructedClass;
}
 
Example 19
Source File: SubclassDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType.Unloaded<T> make(TypeResolutionStrategy typeResolutionStrategy) {
    return make(typeResolutionStrategy, TypePool.ClassLoading.ofSystemLoader()); // Mimics the default behavior of ASM for least surprise.
}
 
Example 20
Source File: ProxyBuildingHelper.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public DynamicType.Unloaded<?> buildUnloadedProxy(Class<?> mappedClass, Class[] interfaces) {
    return getByteBuddyProxyHelper().buildUnloadedProxy(mappedClass, interfaces);
}