net.bytebuddy.implementation.MethodCall Java Examples

The following examples show how to use net.bytebuddy.implementation.MethodCall. 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: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodRegistry inject(TypeDescription instrumentedType, MethodRegistry methodRegistry) {
    MethodList<?> candidates = instrumentedType.getSuperClass().getDeclaredMethods().filter(isConstructor().and(elementMatcher));
    if (candidates.isEmpty()) {
        throw new IllegalStateException("No possible candidate for super constructor invocation in " + instrumentedType.getSuperClass());
    } else if (!candidates.filter(takesArguments(0)).isEmpty()) {
        candidates = candidates.filter(takesArguments(0));
    } else if (candidates.size() > 1) {
        throw new IllegalStateException("More than one possible super constructor for constructor delegation: " + candidates);
    }
    MethodCall methodCall = MethodCall.invoke(candidates.getOnly());
    for (TypeDescription typeDescription : candidates.getOnly().getParameters().asTypeList().asErasures()) {
        methodCall = methodCall.with(typeDescription.getDefaultValue());
    }
    return methodRegistry.append(new LatentMatcher.Resolved<MethodDescription>(isConstructor().and(takesArguments(0))),
            new MethodRegistry.Handler.ForImplementation(methodCall),
            methodAttributeAppenderFactory,
            Transformer.NoOp.<MethodDescription>make());
}
 
Example #2
Source File: ClassInjectorUsingLookupTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    type = new ByteBuddy()
            .subclass(Object.class)
            .name("net.bytebuddy.test.Foo")
            .defineMethod("lookup", Object.class, Ownership.STATIC, Visibility.PUBLIC)
            .intercept(MethodCall.invoke(Class.forName("java.lang.invoke.MethodHandles").getMethod("lookup")))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
}
 
Example #3
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 #4
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static synchronized Parser newParser(Context ctx, NBParserFactory fac,
                                             Lexer S, boolean keepDocComments,
                                             boolean keepLineMap, CancelService cancelService,
                                             Names names) {
    try {
        if (parserClass == null) {
            Method switchBlockStatementGroup = JavacParser.class.getDeclaredMethod("switchBlockStatementGroup");
            Method delegate;
            if (switchBlockStatementGroup.getReturnType().equals(com.sun.tools.javac.util.List.class)) {
                delegate = JackpotJavacParser.class.getDeclaredMethod("switchBlockStatementGroupListImpl");
            } else {
                delegate = JackpotJavacParser.class.getDeclaredMethod("switchBlockStatementGroupImpl");
            }
            parserClass = load(new ByteBuddy()
                                .subclass(JackpotJavacParser.class)
                                .method(ElementMatchers.named("switchBlockStatementGroup")).intercept(MethodCall.invoke(delegate))
                                .make())
                        .getLoaded();
        }
        return (Parser) parserClass.getConstructor(Context.class, NBParserFactory.class, Lexer.class, boolean.class, boolean.class, CancelService.class, Names.class)
                .newInstance(ctx, fac, S, keepDocComments, keepLineMap, cancelService, names);
    } catch (ReflectiveOperationException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #5
Source File: ThrowableSanitiser.java    From styx with Apache License 2.0 5 votes vote down vote up
/**
 * Wrap a {@link Throwable} in a dynamic proxy that sanitizes its message to hide sensitive cookie
 * information. The supplied Throwable must be non-final, and must have a no-args constructor. If the proxy
 * cannot be created for any reason (including that it is proxying a final class, or one without a no-args constructor),
 * then a warning is logged and the unproxied Throwable is returned back to the caller.
 * @param original the Throwable to be proxied
 * @param formatter hides the sensitive cookies.
 * @return the proxied Throwable, or the original throwable if it cannot be proxied.
 */
public Throwable sanitise(Throwable original, SanitisedHttpHeaderFormatter formatter) {

    Class<?> clazz = original.getClass();
    try {
        Constructor<?> defaultConstructor = clazz.getConstructor();

        Class<?> proxyClass = typeCache.findOrInsert(getClass().getClassLoader(), clazz.getName(), () ->
                new ByteBuddy()
                        .subclass(clazz)
                        .defineField("methodInterceptor", Interceptor.class, Visibility.PRIVATE)
                        .defineConstructor(Visibility.PUBLIC)
                        .withParameters(Interceptor.class)
                        .intercept(FieldAccessor.ofField("methodInterceptor").setsArgumentAt(0)
                                .andThen(MethodCall.invoke(defaultConstructor)))
                        .method(ElementMatchers.any())
                        .intercept(MethodDelegation.toField("methodInterceptor"))
                        .make()
                        .load(getClass().getClassLoader())
                        .getLoaded());

        return (Throwable) proxyClass
                .getConstructor(Interceptor.class)
                .newInstance(new Interceptor(original, formatter));
    } catch (Exception e) {
        LOG.warn("Unable to proxy throwable class {} - {}", clazz, e.toString()); // No need to log stack trace here
    }
    return original;
}
 
Example #6
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 #7
Source File: RedefinitionDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructorRebaseSingleAuxiliaryType() throws Exception {
    DynamicType.Unloaded<?> dynamicType = new ByteBuddy()
            .redefine(Bar.class)
            .constructor(any()).intercept(MethodCall.invoke(Object.class.getDeclaredConstructor()))
            .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(0));
    Field field = type.getDeclaredField(BAR);
    assertThat(field.get(type.getDeclaredConstructor(String.class).newInstance(FOO)), nullValue(Object.class));
}
 
Example #8
Source File: AbstractDynamicTypeBuilderForInliningTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeInitializerRetention() throws Exception {
    Class<?> type = create(Qux.class)
            .invokable(isTypeInitializer()).intercept(MethodCall.invoke(Qux.class.getDeclaredMethod("invoke")))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredConstructor().newInstance(), notNullValue(Object.class));
    assertThat(type.getDeclaredField(FOO).get(null), is((Object) FOO));
    assertThat(type.getDeclaredField(BAR).get(null), is((Object) BAR));
}
 
Example #9
Source File: JackpotTrees.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static <T> T createInstance(Context ctx, Class<T> clazz, Name ident, JCIdent jcIdent, Class<?>[] requiredConstructor, Object[] params) {
    try {
        Class<?> fake = baseClass2Impl.get(clazz);

        if (fake == null) {
            Method visitIdent = Visitor.class.getDeclaredMethod("visitIdent", JCIdent.class);
            Method visitIdentifier = TreeVisitor.class.getDeclaredMethod("visitIdentifier", IdentifierTree.class, Object.class);
            Method toString = Object.class.getDeclaredMethod("toString");
            fake = Utilities.load(new ByteBuddy()
                    .subclass(clazz)
                    .implement(IdentifierTree.class)
                    .defineField("ident", Name.class, Visibility.PUBLIC)
                    .defineField("jcIdent", JCIdent.class, Visibility.PUBLIC)
                    .method(ElementMatchers.named("getName")).intercept(FieldAccessor.ofField("ident"))
                    .method(ElementMatchers.named("getKind")).intercept(FixedValue.value(Kind.IDENTIFIER))
                    .method(ElementMatchers.named("accept").and(ElementMatchers.takesArguments(Visitor.class))).intercept(MethodCall.invoke(visitIdent).onArgument(0).withField("jcIdent"))
                    .method(ElementMatchers.named("accept").and(ElementMatchers.takesArgument(0, TreeVisitor.class))).intercept(MethodCall.invoke(visitIdentifier).onArgument(0).withThis().withArgument(1))
                    .method(ElementMatchers.named("toString")).intercept(MethodCall.invoke(toString).onField("ident"))
                    .name(JackpotTrees.class.getCanonicalName() + "$" + clazz.getCanonicalName().replace('.', '$'))
                    .make())
                    .getLoaded();
            baseClass2Impl.put(clazz, fake);
        }

        NEXT: for (Constructor c : fake.getDeclaredConstructors()) {
            if (c.getParameterCount() < requiredConstructor.length)
                continue;
            for (int e = 0; e < requiredConstructor.length; e++) {
                if (!c.getParameterTypes()[e].equals(requiredConstructor[e])) {
                    continue NEXT;
                }
            }
            java.util.List<Object> instances = new ArrayList<>();
            instances.addAll(Arrays.asList(params));
            for (int i = instances.size(); i < c.getParameterCount(); i++) {
                instances.add(null);
            }

            JCTree tree = (JCTree) c.newInstance(instances.toArray(new Object[0]));

            Field identField = fake.getDeclaredField("ident");

            identField.set(tree, ident);

            Field jcIdentField = fake.getDeclaredField("jcIdent");

            jcIdentField.set(tree, jcIdent);

            return clazz.cast(tree);
        }

        throw new IllegalStateException(Arrays.asList(fake.getDeclaredConstructors()).toString());
    } catch (IllegalAccessException | IllegalArgumentException | IllegalStateException | InstantiationException | NoSuchFieldException | NoSuchMethodException | SecurityException | InvocationTargetException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #10
Source File: BytecodeProviderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ReflectionOptimizer getReflectionOptimizer(
		final Class clazz,
		final String[] getterNames,
		final String[] setterNames,
		final Class[] types) {
	final Class fastClass;
	if ( !clazz.isInterface() && !Modifier.isAbstract( clazz.getModifiers() ) ) {
		// we only provide a fast class instantiator if the class can be instantiated
		final Constructor<?> constructor = findConstructor( clazz );

		fastClass = byteBuddyState.load( clazz, byteBuddy -> byteBuddy
				.with( new NamingStrategy.SuffixingRandom( INSTANTIATOR_PROXY_NAMING_SUFFIX,
						new NamingStrategy.SuffixingRandom.BaseNameResolver.ForFixedValue( clazz.getName() ) ) )
				.subclass( ReflectionOptimizer.InstantiationOptimizer.class )
				.method( newInstanceMethodName )
						.intercept( MethodCall.construct( constructor ) )
		);
	}
	else {
		fastClass = null;
	}

	final Method[] getters = new Method[getterNames.length];
	final Method[] setters = new Method[setterNames.length];
	findAccessors( clazz, getterNames, setterNames, types, getters, setters );

	final Class bulkAccessor = byteBuddyState.load( clazz, byteBuddy -> byteBuddy
			.with( new NamingStrategy.SuffixingRandom( OPTIMIZER_PROXY_NAMING_SUFFIX,
					new NamingStrategy.SuffixingRandom.BaseNameResolver.ForFixedValue( clazz.getName() ) ) )
			.subclass( ReflectionOptimizer.AccessOptimizer.class )
			.method( getPropertyValuesMethodName )
					.intercept( new Implementation.Simple( new GetPropertyValues( clazz, getters ) ) )
			.method( setPropertyValuesMethodName )
					.intercept( new Implementation.Simple( new SetPropertyValues( clazz, setters ) ) )
			.method( getPropertyNamesMethodName )
					.intercept( MethodCall.call( new CloningPropertyCall( getterNames ) ) )
	);

	try {
		return new ReflectionOptimizerImpl(
				fastClass != null ? (ReflectionOptimizer.InstantiationOptimizer) fastClass.newInstance() : null,
				(ReflectionOptimizer.AccessOptimizer) bulkAccessor.newInstance()
		);
	}
	catch (Exception exception) {
		throw new HibernateException( exception );
	}
}