net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy Java Examples

The following examples show how to use net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy. 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: ByteBuddyProxyHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public Class buildProxy(
		final Class persistentClass,
		final Class[] interfaces) {
	Set<Class<?>> key = new HashSet<Class<?>>();
	if ( interfaces.length == 1 ) {
		key.add( persistentClass );
	}
	key.addAll( Arrays.<Class<?>>asList( interfaces ) );

	return byteBuddyState.loadProxy( persistentClass, new TypeCache.SimpleKey(key), byteBuddy -> byteBuddy
			.ignore( byteBuddyState.getProxyDefinitionHelpers().getGroovyGetMetaClassFilter() )
			.with( new NamingStrategy.SuffixingRandom( PROXY_NAMING_SUFFIX, new NamingStrategy.SuffixingRandom.BaseNameResolver.ForFixedValue( persistentClass.getName() ) ) )
			.subclass( interfaces.length == 1 ? persistentClass : Object.class, ConstructorStrategy.Default.IMITATE_SUPER_CLASS_OPENING )
			.implement( (Type[]) interfaces )
			.method( byteBuddyState.getProxyDefinitionHelpers().getVirtualNotFinalizerFilter() )
					.intercept( byteBuddyState.getProxyDefinitionHelpers().getDelegateToInterceptorDispatcherMethodDelegation() )
			.method( byteBuddyState.getProxyDefinitionHelpers().getHibernateGeneratedMethodFilter() )
					.intercept( SuperMethodCall.INSTANCE )
			.defineField( ProxyConfiguration.INTERCEPTOR_FIELD_NAME, ProxyConfiguration.Interceptor.class, Visibility.PRIVATE )
			.implement( ProxyConfiguration.class )
					.intercept( byteBuddyState.getProxyDefinitionHelpers().getInterceptorFieldAccessor() )
	);
}
 
Example #2
Source File: BasicProxyFactoryImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public BasicProxyFactoryImpl(Class superClass, Class[] interfaces, ByteBuddyState byteBuddyState) {
	if ( superClass == null && ( interfaces == null || interfaces.length < 1 ) ) {
		throw new AssertionFailure( "attempting to build proxy without any superclass or interfaces" );
	}

	final Class<?> superClassOrMainInterface = superClass != null ? superClass : interfaces[0];
	final TypeCache.SimpleKey cacheKey = getCacheKey( superClass, interfaces );

	this.proxyClass = byteBuddyState.loadBasicProxy( superClassOrMainInterface, cacheKey, byteBuddy -> byteBuddy
			.with( new NamingStrategy.SuffixingRandom( PROXY_NAMING_SUFFIX, new NamingStrategy.SuffixingRandom.BaseNameResolver.ForFixedValue( superClassOrMainInterface.getName() ) ) )
			.subclass( superClass == null ? Object.class : superClass, ConstructorStrategy.Default.DEFAULT_CONSTRUCTOR )
			.implement( interfaces == null ? NO_INTERFACES : interfaces )
			.defineField( ProxyConfiguration.INTERCEPTOR_FIELD_NAME, ProxyConfiguration.Interceptor.class, Visibility.PRIVATE )
			.method( byteBuddyState.getProxyDefinitionHelpers().getVirtualNotFinalizerFilter() )
					.intercept( byteBuddyState.getProxyDefinitionHelpers().getDelegateToInterceptorDispatcherMethodDelegation() )
			.implement( ProxyConfiguration.class )
					.intercept( byteBuddyState.getProxyDefinitionHelpers().getInterceptorFieldAccessor() )
	);
	this.interceptor = new PassThroughInterceptor( proxyClass.getName() );
}
 
Example #3
Source File: MethodCaptor.java    From reflection-util with Apache License 2.0 6 votes vote down vote up
static <T> Class<? extends T> createProxyClass(Class<T> beanClass) {
	try {
		return new ByteBuddy()
			.subclass(beanClass, ConstructorStrategy.Default.NO_CONSTRUCTORS)
			.defineField(MethodCaptor.FIELD_NAME, MethodCaptor.class, Visibility.PRIVATE)
			.method(isMethod()
				.and(takesArguments(0))
				.and(not(isDeclaredBy(Object.class))))
			.intercept(MethodDelegation.to(MethodCaptor.class))
			.make()
			.load(PropertyUtils.class.getClassLoader())
			.getLoaded();
	} catch (IllegalAccessError e) {
		throw new ReflectionRuntimeException("Failed to create proxy on " + beanClass, e);
	}
}
 
Example #4
Source File: QualifierAndScopeImplementationGenerator.java    From Diorite with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #5
Source File: ByteBuddyStageClassCreator.java    From JGiven with Apache License 2.0 6 votes vote down vote up
public <T> Class<? extends T> createStageClass( Class<T> stageClass ) {
    return new ByteBuddy()
        .subclass( stageClass, ConstructorStrategy.Default.IMITATE_SUPER_CLASS_OPENING )
        .implement( StageInterceptorInternal.class )
        .defineField( INTERCEPTOR_FIELD_NAME, StepInterceptor.class )
        .method( named(SETTER_NAME) )
            .intercept(
                MethodDelegation.withDefaultConfiguration()
                    .withBinders( FieldProxy.Binder.install(
                            StepInterceptorGetterSetter.class ))
            .to(new StepInterceptorSetter() ))
        .method( not( named( SETTER_NAME )
                .or(ElementMatchers.isDeclaredBy(Object.class))))
        .intercept(
                MethodDelegation.withDefaultConfiguration()
                .withBinders(FieldProxy.Binder.install(
                        StepInterceptorGetterSetter.class ))
            .to( new ByteBuddyMethodInterceptor() ))
        .make()
        .load( getClassLoader(stageClass),
            getClassLoadingStrategy( stageClass ) )
        .getLoaded();
}
 
Example #6
Source File: MethodCallProxy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType make(String auxiliaryTypeName,
                        ClassFileVersion classFileVersion,
                        MethodAccessorFactory methodAccessorFactory) {
    MethodDescription accessorMethod = methodAccessorFactory.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.DEFAULT);
    LinkedHashMap<String, TypeDescription> parameterFields = extractFields(accessorMethod);
    DynamicType.Builder<?> builder = new ByteBuddy(classFileVersion)
            .with(TypeValidation.DISABLED)
            .with(PrecomputedMethodGraph.INSTANCE)
            .subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
            .name(auxiliaryTypeName)
            .modifiers(DEFAULT_TYPE_MODIFIER)
            .implement(Runnable.class, Callable.class).intercept(new MethodCall(accessorMethod, assigner))
            .implement(serializableProxy ? new Class<?>[]{Serializable.class} : new Class<?>[0])
            .defineConstructor().withParameters(parameterFields.values())
            .intercept(ConstructorCall.INSTANCE);
    for (Map.Entry<String, TypeDescription> field : parameterFields.entrySet()) {
        builder = builder.defineField(field.getKey(), field.getValue(), Visibility.PRIVATE);
    }
    return builder.make();
}
 
Example #7
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Creates a new {@link Annotation} type. Annotation properties are implemented as non-static, public methods with the
 * property type being defined as the return type.
 * </p>
 * <p>
 * <b>Note</b>: Byte Buddy does not cache previous subclasses but will attempt the generation of a new subclass. For caching
 * types, a external cache or {@link TypeCache} should be used.
 * </p>
 *
 * @return A type builder that creates a new {@link Annotation} type.
 */
public DynamicType.Builder<? extends Annotation> makeAnnotation() {
    return new SubclassDynamicTypeBuilder<Annotation>(instrumentedTypeFactory.subclass(namingStrategy.subclass(TypeDescription.Generic.ANNOTATION),
            ModifierContributor.Resolver.of(Visibility.PUBLIC, TypeManifestation.ANNOTATION).resolve(),
            TypeDescription.Generic.OBJECT).withInterfaces(new TypeList.Generic.Explicit(TypeDescription.Generic.ANNOTATION)),
            classFileVersion,
            auxiliaryTypeNamingStrategy,
            annotationValueFilterFactory,
            annotationRetention,
            implementationContextFactory,
            methodGraphCompiler,
            typeValidation,
            visibilityBridgeStrategy,
            classWriterStrategy,
            ignoredMethods,
            ConstructorStrategy.Default.NO_CONSTRUCTORS);
}
 
Example #8
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Creates a new package definition. Package definitions are defined by classes named {@code package-info}
 * without any methods or fields but permit annotations. Any field or method definition will cause an
 * {@link IllegalStateException} to be thrown when the type is created.
 * </p>
 * <p>
 * <b>Note</b>: Byte Buddy does not cache previous subclasses but will attempt the generation of a new subclass. For caching
 * types, a external cache or {@link TypeCache} should be used.
 * </p>
 *
 * @param name The fully qualified name of the package.
 * @return A type builder that creates a {@code package-info} class file.
 */
public DynamicType.Builder<?> makePackage(String name) {
    return new SubclassDynamicTypeBuilder<Object>(instrumentedTypeFactory.subclass(name + "." + PackageDescription.PACKAGE_CLASS_NAME,
            PackageDescription.PACKAGE_MODIFIERS,
            TypeDescription.Generic.OBJECT),
            classFileVersion,
            auxiliaryTypeNamingStrategy,
            annotationValueFilterFactory,
            annotationRetention,
            implementationContextFactory,
            methodGraphCompiler,
            typeValidation,
            visibilityBridgeStrategy,
            classWriterStrategy,
            ignoredMethods,
            ConstructorStrategy.Default.NO_CONSTRUCTORS);
}
 
Example #9
Source File: TypeWriterDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testAbstractConstructorAssertion() throws Exception {
    new ByteBuddy()
            .subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
            .defineConstructor(Visibility.PUBLIC)
            .withoutCode()
            .make();
}
 
Example #10
Source File: ByteBuddyProcessFunctionInvoker.java    From da-streamingledger with Apache License 2.0 5 votes vote down vote up
private static Builder<?> configureByteBuddyBuilder(
        PackageLocalNamingStrategy generatedTypeName,
        TypeDefinition generatedType,
        TypeDefinition processFunctionType,
        ForLoadedConstructor superTypeConstructor,
        MethodDescription processMethodType,
        int numberOfStateBindings) {

    return new ByteBuddy()
            // final class <Name> extends <ProcessFunctionInvoker> {
            .with(generatedTypeName)
            .subclass(generatedType, ConstructorStrategy.Default.NO_CONSTRUCTORS).modifiers(Modifier.FINAL)
            // private final <processFunction class> delegate;
            .defineField("delegate", processFunctionType, Visibility.PRIVATE, FieldManifestation.FINAL)
            // public <Name>(<processFunction class> delegate) {
            //     super();
            //     this.delegate = delegate;
            // }
            .defineConstructor(Modifier.PUBLIC)
            .withParameters(processFunctionType)
            .intercept(MethodCall.invoke(superTypeConstructor)
                    .andThen(FieldAccessor.ofField("delegate").setsArgumentAt(0))
            )
            // invoke(input, context, StateAccess[] arguments) {
            //      this.delegate.invoke(input, context, arguments[0], arguments[1], .. arguments[n - 1]);
            // }
            .method(ElementMatchers.named("invoke"))
            .intercept(MethodCall.invoke(processMethodType)
                    .onField("delegate")
                    .withArgument(0, 1) // event & context
                    .withArgumentArrayElements(2, numberOfStateBindings) // StateAccess
                    .withAssigner(Assigner.DEFAULT, Typing.STATIC)
            );
}
 
Example #11
Source File: MethodCallTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructorIsAccessibleFromDifferentPackage() throws Exception {
    assertThat(new ByteBuddy()
        .subclass(ProtectedConstructor.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
        .name("foo.Bar")
        .defineConstructor(Visibility.PUBLIC)
        .intercept(MethodCall.invoke(ProtectedConstructor.class.getDeclaredConstructor()).onSuper())
        .make()
        .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
        .getLoaded()
        .getConstructor()
        .newInstance(), instanceOf(ProtectedConstructor.class));
}
 
Example #12
Source File: MethodCallTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuperConstructorInvocationUsingMatcher() throws Exception {
    assertThat(new ByteBuddy()
            .subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
            .defineConstructor(Visibility.PUBLIC)
            .intercept(MethodCall.invoke(isConstructor()).onSuper())
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getConstructor()
            .newInstance(), notNullValue(Object.class));
}
 
Example #13
Source File: FieldAccessorOtherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testArgumentSetterConstructor() throws Exception {
    Class<?> loaded = new ByteBuddy()
            .subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
            .defineField(FOO, String.class, Visibility.PUBLIC, FieldManifestation.FINAL)
            .defineConstructor(Visibility.PUBLIC)
            .withParameters(String.class)
            .intercept(MethodCall.invoke(Object.class.getDeclaredConstructor()).andThen(FieldAccessor.ofField(FOO).setsArgumentAt(0)))
            .make()
            .load(null, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(loaded.getDeclaredField(FOO).get(loaded.getDeclaredConstructor(String.class).newInstance(FOO)), is((Object) FOO));
}
 
Example #14
Source File: ByteBuddyTutorialExamplesTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testFieldsAndMethodsExplicitMethodCall() throws Exception {
    Object object = new ByteBuddy()
            .subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
            .defineConstructor(Visibility.PUBLIC).withParameters(int.class)
            .intercept(MethodCall.invoke(Object.class.getDeclaredConstructor()))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor(int.class)
            .newInstance(42);
    assertThat(object.getClass(), CoreMatchers.not(CoreMatchers.<Class<?>>is(Object.class)));
}
 
Example #15
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Creates a new {@link Enum} type.
 * </p>
 * <p>
 * <b>Note</b>: Byte Buddy does not cache previous subclasses but will attempt the generation of a new subclass. For caching
 * types, a external cache or {@link TypeCache} should be used.
 * </p>
 *
 * @param values The names of the type's enumeration constants
 * @return A type builder for creating an enumeration type.
 */
public DynamicType.Builder<? extends Enum<?>> makeEnumeration(Collection<? extends String> values) {
    if (values.isEmpty()) {
        throw new IllegalArgumentException("Require at least one enumeration constant");
    }
    TypeDescription.Generic enumType = TypeDescription.Generic.Builder.parameterizedType(Enum.class, TargetType.class).build();
    return new SubclassDynamicTypeBuilder<Enum<?>>(instrumentedTypeFactory.subclass(namingStrategy.subclass(enumType),
            ModifierContributor.Resolver.of(Visibility.PUBLIC, TypeManifestation.FINAL, EnumerationState.ENUMERATION).resolve(),
            enumType),
            classFileVersion,
            auxiliaryTypeNamingStrategy,
            annotationValueFilterFactory,
            annotationRetention,
            implementationContextFactory,
            methodGraphCompiler,
            typeValidation,
            visibilityBridgeStrategy,
            classWriterStrategy,
            ignoredMethods,
            ConstructorStrategy.Default.NO_CONSTRUCTORS)
            .defineConstructor(Visibility.PRIVATE).withParameters(String.class, int.class)
            .intercept(SuperMethodCall.INSTANCE)
            .defineMethod(EnumerationImplementation.ENUM_VALUE_OF_METHOD_NAME,
                    TargetType.class,
                    Visibility.PUBLIC, Ownership.STATIC).withParameters(String.class)
            .intercept(MethodCall.invoke(enumType.getDeclaredMethods()
                    .filter(named(EnumerationImplementation.ENUM_VALUE_OF_METHOD_NAME).and(takesArguments(Class.class, String.class))).getOnly())
                    .withOwnType().withArgument(0)
                    .withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC))
            .defineMethod(EnumerationImplementation.ENUM_VALUES_METHOD_NAME,
                    TargetType[].class,
                    Visibility.PUBLIC, Ownership.STATIC)
            .intercept(new EnumerationImplementation(new ArrayList<String>(values)));
}
 
Example #16
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Creates a new builder for subclassing the provided type. If the provided type is an interface, a new class implementing
 * this interface type is created.
 * </p>
 * <p>
 * <b>Note</b>: This methods implements the supplied types <i>as is</i>, i.e. any {@link TypeDescription} values are implemented
 * as raw types if they declare type variables.
 * </p>
 * <p>
 * <b>Note</b>: Byte Buddy does not cache previous subclasses but will attempt the generation of a new subclass. For caching
 * types, a external cache or {@link TypeCache} should be used.
 * </p>
 *
 * @param superType           The super class or interface type to extend. The type must be a raw type or parameterized
 *                            type. All type variables that are referenced by the generic type must be declared by the
 *                            generated subclass before creating the type.
 * @param constructorStrategy A constructor strategy that determines the
 * @return A type builder for creating a new class extending the provided class or interface.
 */
public DynamicType.Builder<?> subclass(TypeDefinition superType, ConstructorStrategy constructorStrategy) {
    TypeDescription.Generic actualSuperType;
    TypeList.Generic interfaceTypes;
    if (superType.isPrimitive() || superType.isArray() || superType.isFinal()) {
        throw new IllegalArgumentException("Cannot subclass primitive, array or final types: " + superType);
    } else if (superType.isInterface()) {
        actualSuperType = TypeDescription.Generic.OBJECT;
        interfaceTypes = new TypeList.Generic.Explicit(superType);
    } else {
        actualSuperType = superType.asGenericType();
        interfaceTypes = new TypeList.Generic.Empty();
    }
    return new SubclassDynamicTypeBuilder<Object>(instrumentedTypeFactory.subclass(namingStrategy.subclass(superType.asGenericType()),
            ModifierContributor.Resolver.of(Visibility.PUBLIC, TypeManifestation.PLAIN).resolve(superType.getModifiers()),
            actualSuperType).withInterfaces(interfaceTypes),
            classFileVersion,
            auxiliaryTypeNamingStrategy,
            annotationValueFilterFactory,
            annotationRetention,
            implementationContextFactory,
            methodGraphCompiler,
            typeValidation,
            visibilityBridgeStrategy,
            classWriterStrategy,
            ignoredMethods,
            constructorStrategy);
}
 
Example #17
Source File: PageFragmentImplementation.java    From webtester2-core with Apache License 2.0 5 votes vote down vote up
private static Class<? extends PageFragment> create(Class<? extends PageFragment> pageFragmentType) {

        String className = pageFragmentType.getCanonicalName() + "$$Impl";
        ClassLoader classLoader = pageFragmentType.getClassLoader();

        InvocationHandler identifyUsingHandler = new IdentifyUsingInvocationHandler();
        InvocationHandler attributeHandler = new AttributeInvocationHandler();

        Builder<BasePageFragment> pageFragmentTypeBuilder = new ByteBuddy()//
            .with(ClassFileVersion.JAVA_V8)
            .subclass(BasePageFragment.class, ConstructorStrategy.Default.IMITATE_SUPER_CLASS)
            .implement(pageFragmentType)
            .name(className);

        if (ClasspathUtils.KOTLIN_MODULE_LOADED) {
            pageFragmentTypeBuilder = addKotlinImplementations(pageFragmentTypeBuilder, pageFragmentType);
        }

        pageFragmentTypeBuilder = pageFragmentTypeBuilder//
            .method(isDefaultMethod())//
            .intercept(Advice.to(ActionAdvice.class)//
                .wrap(Advice.to(MarkingAdvice.class)//
                    .wrap(Advice.to(EventProducerAdvice.class)//
                        .wrap(DefaultMethodCall.prioritize(pageFragmentType)))));

        pageFragmentTypeBuilder = pageFragmentTypeBuilder//
            .method(isAbstract().and(isAnnotatedWith(IdentifyUsing.class)).and(takesArguments(0)))
            .intercept(InvocationHandlerAdapter.of(identifyUsingHandler));

        pageFragmentTypeBuilder = pageFragmentTypeBuilder//
            .method(isAbstract().and(isAnnotatedWith(Attribute.class)).and(takesArguments(0)))
            .intercept(Advice.to(MarkingAdvice.class)//
                .wrap(InvocationHandlerAdapter.of(attributeHandler)));

        return pageFragmentTypeBuilder.make().load(classLoader).getLoaded();

    }
 
Example #18
Source File: PageImplementation.java    From webtester2-core with Apache License 2.0 5 votes vote down vote up
private static Class<? extends Page> create(Class<? extends Page> pageType) {

        String className = pageType.getCanonicalName() + "$$Impl";
        ClassLoader classLoader = pageType.getClassLoader();

        InvocationHandler identifyUsingHandler = new IdentifyUsingInvocationHandler();

        Builder<BasePage> pageTypeBuilder = new ByteBuddy()//
            .with(ClassFileVersion.JAVA_V8)
            .subclass(BasePage.class, ConstructorStrategy.Default.IMITATE_SUPER_CLASS)
            .implement(pageType)
            .name(className);

        if (ClasspathUtils.KOTLIN_MODULE_LOADED) {
            pageTypeBuilder = addKotlinImplementations(pageTypeBuilder, pageType);
        }

        pageTypeBuilder = pageTypeBuilder//
            .method(isDefaultMethod())//
            .intercept(Advice.to(ActionAdvice.class)//
                .wrap(DefaultMethodCall.prioritize(pageType)));

        pageTypeBuilder = pageTypeBuilder//
            .method(isAbstract().and(isAnnotatedWith(IdentifyUsing.class)).and(takesArguments(0)))
            .intercept(InvocationHandlerAdapter.of(identifyUsingHandler));

        return pageTypeBuilder.make().load(classLoader).getLoaded();

    }
 
Example #19
Source File: PropertyMutatorCollector.java    From jackson-modules-base with Apache License 2.0 4 votes vote down vote up
public Class<?> generateMutatorClass(MyClassLoader classLoader, ClassName baseName)
{
    DynamicType.Builder<?> builder =
            new ByteBuddy(ClassFileVersion.JAVA_V6)
                    .with(TypeValidation.DISABLED)
                    .subclass(BeanPropertyMutator.class, ConstructorStrategy.Default.DEFAULT_CONSTRUCTOR)
                    .name(baseName.getSlashedTemplate())
                    .modifiers(Visibility.PUBLIC, TypeManifestation.FINAL);


    // and then add various accessors; first field accessors:
    if (!_intFields.isEmpty()) {
        builder = _addFields(builder, _intFields, "intField", MethodVariableAccess.INTEGER);
    }
    if (!_longFields.isEmpty()) {
        builder = _addFields(builder, _longFields, "longField", MethodVariableAccess.LONG);
    }
    if (!_booleanFields.isEmpty()) {
        // booleans are simply ints 0 and 1
        builder = _addFields(builder, _booleanFields, "booleanField", MethodVariableAccess.INTEGER);
    }
    if (!_stringFields.isEmpty()) {
        builder = _addFields(builder, _stringFields, "stringField", MethodVariableAccess.REFERENCE);
    }
    if (!_objectFields.isEmpty()) {
        builder = _addFields(builder, _objectFields, "objectField", MethodVariableAccess.REFERENCE);
    }

    // and then method accessors:
    if (!_intSetters.isEmpty()) {
        builder = _addSetters(builder, _intSetters, "intSetter", MethodVariableAccess.INTEGER);
    }
    if (!_longSetters.isEmpty()) {
        builder = _addSetters(builder, _longSetters, "longSetter", MethodVariableAccess.LONG);
    }
    if (!_booleanSetters.isEmpty()) {
        // booleans are simply ints 0 and 1
        builder = _addSetters(builder, _booleanSetters, "booleanSetter", MethodVariableAccess.INTEGER);
    }
    if (!_stringSetters.isEmpty()) {
        builder = _addSetters(builder, _stringSetters, "stringSetter", MethodVariableAccess.REFERENCE);
    }
    if (!_objectSetters.isEmpty()) {
        builder = _addSetters(builder, _objectSetters, "objectSetter", MethodVariableAccess.REFERENCE);
    }

    byte[] bytecode = builder.make().getBytes();
    baseName.assignChecksum(bytecode);
    // already defined exactly as-is?

    try {
        return classLoader.loadClass(baseName.getDottedName());
    } catch (ClassNotFoundException e) { }
    // if not, load, resolve etc:
    return classLoader.loadAndResolve(baseName, bytecode);
}
 
Example #20
Source File: PropertyAccessorCollector.java    From jackson-modules-base with Apache License 2.0 4 votes vote down vote up
public Class<?> generateAccessorClass(MyClassLoader classLoader, ClassName baseName)
{
    DynamicType.Builder<?> builder =
            new ByteBuddy(ClassFileVersion.JAVA_V6)
                    .with(TypeValidation.DISABLED)
                    .subclass(BeanPropertyAccessor.class, ConstructorStrategy.Default.DEFAULT_CONSTRUCTOR)
                    .name(baseName.getSlashedTemplate())
                    .modifiers(Visibility.PUBLIC, TypeManifestation.FINAL);

    // and then add various accessors; first field accessors:
    if (!_intFields.isEmpty()) {
        builder = _addFields(builder, _intFields, "intField", MethodReturn.INTEGER);
    }
    if (!_longFields.isEmpty()) {
        builder = _addFields(builder, _longFields, "longField", MethodReturn.LONG);
    }
    if (!_stringFields.isEmpty()) {
        builder = _addFields(builder, _stringFields, "stringField", MethodReturn.REFERENCE);
    }
    if (!_objectFields.isEmpty()) {
        builder = _addFields(builder, _objectFields, "objectField", MethodReturn.REFERENCE);
    }
    if (!_booleanFields.isEmpty()) {
        // booleans treated as ints 0 (false) and 1 (true)
        builder = _addFields(builder, _booleanFields, "booleanField", MethodReturn.INTEGER);
    }

    // and then method accessors:
    if (!_intGetters.isEmpty()) {
        builder = _addGetters(builder, _intGetters, "intGetter", MethodReturn.INTEGER);
    }
    if (!_longGetters.isEmpty()) {
        builder = _addGetters(builder, _longGetters, "longGetter", MethodReturn.LONG);
    }
    if (!_stringGetters.isEmpty()) {
        builder = _addGetters(builder, _stringGetters, "stringGetter", MethodReturn.REFERENCE);
    }
    if (!_objectGetters.isEmpty()) {
        builder = _addGetters(builder, _objectGetters, "objectGetter", MethodReturn.REFERENCE);
    }
    if (!_booleanGetters.isEmpty()) {
        builder = _addGetters(builder, _booleanGetters, "booleanGetter", MethodReturn.INTEGER);
    }

    byte[] bytecode = builder.make().getBytes();
    baseName.assignChecksum(bytecode);

    // Did we already generate this?
    try {
        return classLoader.loadClass(baseName.getDottedName());
    } catch (ClassNotFoundException e) { }
    // if not, load and resolve:
    return classLoader.loadAndResolve(baseName, bytecode);
}
 
Example #21
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Creates a new interface type that extends the provided interface.
 * </p>
 * <p>
 * <b>Note</b>: This methods implements the supplied types <i>as is</i>, i.e. any {@link TypeDescription} values are implemented
 * as raw types if they declare type variables or an owner type.
 * </p>
 * <p>
 * <b>Note</b>: Byte Buddy does not cache previous subclasses but will attempt the generation of a new subclass. For caching
 * types, a external cache or {@link TypeCache} should be used.
 * </p>
 *
 * @param interfaceTypes The interface types to implement. The types must be raw or parameterized types. All
 *                       type variables that are referenced by a parameterized type must be declared by the
 *                       generated subclass before creating the type.
 * @return A type builder that creates a new interface type.
 */
public DynamicType.Builder<?> makeInterface(Collection<? extends TypeDefinition> interfaceTypes) {
    return subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS).implement(interfaceTypes).modifiers(TypeManifestation.INTERFACE, Visibility.PUBLIC);
}
 
Example #22
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Creates a new builder for subclassing the provided type. If the provided type is an interface, a new class implementing
 * this interface type is created.
 * </p>
 * <p>
 * When extending a class, Byte Buddy imitates all visible constructors of the subclassed type and sets them to be {@code public}.
 * Any constructor is implemented to only invoke its super type constructor of equal signature. Another behavior can be specified by
 * supplying an explicit {@link ConstructorStrategy} by {@link ByteBuddy#subclass(TypeDefinition, ConstructorStrategy)}.
 * </p>
 * <p>
 * <b>Note</b>: This methods implements the supplied types <i>as is</i>, i.e. any {@link TypeDescription} values are implemented
 * as raw types if they declare type variables.
 * </p>
 * <p>
 * <b>Note</b>: Byte Buddy does not cache previous subclasses but will attempt the generation of a new subclass. For caching
 * types, a external cache or {@link TypeCache} should be used.
 * </p>
 *
 * @param superType The super class or interface type to extend. The type must be a raw type or parameterized type. All type
 *                  variables that are referenced by the generic type must be declared by the generated subclass before creating
 *                  the type.
 * @return A type builder for creating a new class extending the provided class or interface.
 */
public DynamicType.Builder<?> subclass(TypeDefinition superType) {
    return subclass(superType, ConstructorStrategy.Default.IMITATE_SUPER_CLASS_OPENING);
}
 
Example #23
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Creates a new builder for subclassing the provided type. If the provided type is an interface, a new class implementing
 * this interface type is created.
 * </p>
 * <p>
 * <b>Note</b>: This methods implements the supplied types <i>as is</i>, i.e. any {@link Class} values are implemented
 * as raw types if they declare type variables.
 * </p>
 * <p>
 * <b>Note</b>: Byte Buddy does not cache previous subclasses but will attempt the generation of a new subclass. For caching
 * types, a external cache or {@link TypeCache} should be used.
 * </p>
 *
 * @param superType           The super class or interface type to extend. The type must be a raw type or parameterized
 *                            type. All type variables that are referenced by the generic type must be declared by the
 *                            generated subclass before creating the type.
 * @param constructorStrategy A constructor strategy that determines the
 * @return A type builder for creating a new class extending the provided class or interface.
 */
public DynamicType.Builder<?> subclass(Type superType, ConstructorStrategy constructorStrategy) {
    return subclass(TypeDefinition.Sort.describe(superType), constructorStrategy);
}
 
Example #24
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Creates a new builder for subclassing the provided type. If the provided type is an interface, a new class implementing
 * this interface type is created.
 * </p>
 * <p>
 * <b>Note</b>: This methods implements the supplied types in a generified state if they declare type variables or an owner type.
 * </p>
 * <p>
 * <b>Note</b>: Byte Buddy does not cache previous subclasses but will attempt the generation of a new subclass. For caching
 * types, a external cache or {@link TypeCache} should be used.
 * </p>
 *
 * @param superType           The super class or interface type to extend.
 * @param constructorStrategy A constructor strategy that determines the
 * @param <T>                 A loaded type that the generated class is guaranteed to inherit.
 * @return A type builder for creating a new class extending the provided class or interface.
 */
@SuppressWarnings("unchecked")
public <T> DynamicType.Builder<T> subclass(Class<T> superType, ConstructorStrategy constructorStrategy) {
    return (DynamicType.Builder<T>) subclass(TypeDescription.ForLoadedType.of(superType), constructorStrategy);
}