Refine search
/** * Makes sure that this transformer is only applied on Freemarker versions {@code >= 2.3.23} where the * {@link Environment#getCurrentTemplate()} method was made public. This prevents nasty * {@link IllegalAccessError}s and {@link NoSuchMethodError}s. */ @Override public boolean isActive() { try { return hasMethodThat(named("getCurrentTemplate") .and(ElementMatchers.<MethodDescription.InDefinedShape>isPublic()) .and(takesArguments(0))) .matches(new TypeDescription.ForLoadedType(Class.forName("freemarker.core.Environment"))); } catch (ClassNotFoundException e) { return false; } }
Map<String, Class<?>> availableTypes = new HashMap<String, Class<?>>(preregisteredTypes); for (Class<?> type : instrumentation.getInitiatedClasses(classLoader)) { availableTypes.put(TypeDescription.ForLoadedType.getName(type), type); Map<TypeDescription, byte[]> unloadedClasses = new LinkedHashMap<TypeDescription, byte[]>(); for (Map.Entry<TypeDescription, byte[]> entry : types.entrySet()) { Class<?> type = availableTypes.get(entry.getKey().getName()); if (type != null) { classDefinitions.put(type, new ClassDefinition(type, entry.getValue()));
private <T> void registerClassInternal(Class<T> entityClass) { DynamicType.Builder<T> builder = new ByteBuddy() .subclass(entityClass); for (FieldDescription.InDefinedShape field : Introspectior.getTypeDescription(LiveObjectTemplate.class) .getDeclaredFields()) { builder = builder.define(field); Class<? extends T> proxied = builder.method(ElementMatchers.isDeclaredBy( Introspectior.getTypeDescription(RLiveObject.class)) .and(ElementMatchers.isGetter().or(ElementMatchers.isSetter()) .or(ElementMatchers.named("isPhantom")) .or(ElementMatchers.named("delete"))))
String lambdaClassName = targetType.getName() + LAMBDA_TYPE_INFIX + LAMBDA_NAME_COUNTER.incrementAndGet(); DynamicType.Builder<?> builder = byteBuddy .subclass(factoryMethod.getReturnType(), ConstructorStrategy.Default.NO_CONSTRUCTORS) .modifiers(TypeManifestation.FINAL, Visibility.PUBLIC) .implement(markerInterfaces) .withParameters(factoryMethod.getParameterTypes()) .intercept(ConstructorImplementation.INSTANCE) .method(named(lambdaMethodName) .and(takesArguments(lambdaMethod.getParameterTypes())) .and(returns(lambdaMethod.getReturnType()))) .intercept(new LambdaMethodImplementation(targetMethod, specializedLambdaMethod)); int index = 0; .intercept(new SerializationImplementation(TypeDescription.ForLoadedType.of(targetType), factoryMethod.getReturnType(), lambdaMethodName, targetMethod, JavaConstant.MethodType.ofLoaded(specializedLambdaMethodType))); } else if (factoryMethod.getReturnType().isAssignableTo(Serializable.class)) { builder = builder.defineMethod("readObject", void.class, Visibility.PRIVATE) .withParameters(ObjectInputStream.class)
@Override public final void check() throws Exception { final TypeDescription typeDescription = new TypeDescription.ForLoadedType(type); final DynamicType.Builder<?> subclass = new ByteBuddy().redefine(type); final DynamicType.Unloaded<?> make = builderTransition .transitionResult(subclass, typeDescription) .make(); final Class<?> clazz = make.load(new AnonymousClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST).getLoaded(); assertThat(clazz.getAnnotation(annotation)) .withFailMessage("Expected annotation %s is missing on class %s", annotation.getName(), clazz.getName()) .isNotNull(); }
AbstractTask<?> createConcreteImplementation(Class<?> type) return new ByteBuddy() .subclass(AbstractTask.class) .method(named("getDataObjectClass")) .intercept(FixedValue.value(new TypeDescription.ForLoadedType(type))) // (*) .make() .load(type.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); }
/** * Ctor. */ public SmtInvokeStringBuilderAppend() { super( new TypeDescription.ForLoadedType(StringBuilder.class), new ConjunctionMatcher<>( ElementMatchers.named("append"), ElementMatchers.takesArguments(1), ElementMatchers.takesArgument(0, Object.class), ElementMatchers.returns(StringBuilder.class) ) ); } }
/** * <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); }
public static FieldDescription getFieldDescription(Class<?> c, String field) { if (field == null || field.isEmpty()) { return null; } return getTypeDescription(c) .getDeclaredFields() .filter(ElementMatchers.named(field)) .getOnly(); }
/** * Creates the singleton instance. */ @SuppressFBWarnings(value = "SE_BAD_FIELD_STORE", justification = "Fields of enumerations are never serialized") AbstractMethodErrorThrow() { TypeDescription abstractMethodError = TypeDescription.ForLoadedType.of(AbstractMethodError.class); MethodDescription constructor = abstractMethodError.getDeclaredMethods() .filter(isConstructor().and(takesArguments(0))).getOnly(); implementation = new Compound(TypeCreation.of(abstractMethodError), Duplication.SINGLE, MethodInvocation.invoke(constructor), Throw.INSTANCE); }
TypeDescription serializedLambda; try { serializedLambda = TypeDescription.ForLoadedType.of(Class.forName("java.lang.invoke.SerializedLambda")); } catch (ClassNotFoundException exception) { throw new IllegalStateException("Cannot find class for lambda serialization", exception); List<StackManipulation> lambdaArguments = new ArrayList<StackManipulation>(implementationTarget.getInstrumentedType().getDeclaredFields().size()); for (FieldDescription.InDefinedShape fieldDescription : implementationTarget.getInstrumentedType().getDeclaredFields()) { lambdaArguments.add(new StackManipulation.Compound(MethodVariableAccess.loadThis(), FieldAccess.forField(fieldDescription).read(), Duplication.SINGLE, ClassConstant.of(targetType), new TextConstant(lambdaType.getInternalName()), new TextConstant(lambdaMethodName), new TextConstant(lambdaMethod.getDescriptor()), new TextConstant(specializedMethod.getDescriptor()), ArrayFactory.forType(TypeDescription.Generic.OBJECT).withValues(lambdaArguments), MethodInvocation.invoke(serializedLambda.getDeclaredMethods().filter(isConstructor()).getOnly()), MethodReturn.REFERENCE ));
argument = ((Class<?>) argument).isPrimitive() ? ofPrimitiveType((Class<?>) argument) : TypeDescription.ForLoadedType.of((Class<?>) argument); } else if (argument instanceof TypeDescription && ((TypeDescription) argument).isPrimitive()) { argument = ofPrimitiveType((TypeDescription) argument); } else if (JavaType.METHOD_HANDLE.getTypeStub().isInstance(argument)) { argument = MethodHandle.ofLoaded(argument); } else if (JavaType.METHOD_TYPE.getTypeStub().isInstance(argument)) { argument = MethodType.ofLoaded(argument); targetType = TypeDescription.CLASS; } else { targetType = TypeDescription.ForLoadedType.of(argument.getClass()); if (!targetType.asBoxed().isAssignableTo(iterator.next().asBoxed())) {
/** * Creates a plugin for caching method return values. */ public CachedReturnPlugin() { super(declaresMethod(isAnnotatedWith(Enhance.class))); randomString = new RandomString(); classFileLocator = ClassFileLocator.ForClassLoader.of(CachedReturnPlugin.class.getClassLoader()); TypePool typePool = TypePool.Default.of(classFileLocator); adviceByType = new HashMap<TypeDescription, TypeDescription>(); for (Class<?> type : new Class<?>[]{ boolean.class, byte.class, short.class, char.class, int.class, long.class, float.class, double.class, Object.class }) { adviceByType.put(TypeDescription.ForLoadedType.ForLoadedType.of(type), typePool.describe(CachedReturnPlugin.class.getName() + ADVICE_INFIX + type.getSimpleName()).resolve()); } }
argument = ((Class<?>) argument).isPrimitive() ? ofPrimitiveType((Class<?>) argument) : TypeDescription.ForLoadedType.of((Class<?>) argument); } else if (argument instanceof TypeDescription && ((TypeDescription) argument).isPrimitive()) { argument = ofPrimitiveType((TypeDescription) argument); } else if (JavaType.METHOD_HANDLE.getTypeStub().isInstance(argument)) { argument = MethodHandle.ofLoaded(argument); } else if (JavaType.METHOD_TYPE.getTypeStub().isInstance(argument)) { argument = MethodType.ofLoaded(argument);
/** * {@inheritDoc} */ public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) { TypeDescription auxiliaryType = implementationContext.register(PrivilegedMemberLookupAction.of(methodDescription)); return new Compound( TypeCreation.of(auxiliaryType), Duplication.SINGLE, ClassConstant.of(methodDescription.getDeclaringType()), methodName, ArrayFactory.forType(TypeDescription.Generic.OfNonGenericType.CLASS) .withValues(typeConstantsFor(methodDescription.getParameters().asTypeList().asErasures())), MethodInvocation.invoke(auxiliaryType.getDeclaredMethods().filter(isConstructor()).getOnly()), MethodInvocation.invoke(DO_PRIVILEGED), TypeCasting.to(TypeDescription.ForLoadedType.of(methodDescription.isConstructor() ? Constructor.class : Method.class)) ).apply(methodVisitor, implementationContext); }
/** * Matches a {@link ByteCodeElement} for being declared by a given {@link java.lang.Class}. This matcher matches * a declared element's raw declaring type. * * @param type The type that is expected to declare the matched byte code element. * @param <T> The type of the matched object. * @return A matcher for byte code elements being declared by the given {@code type}. */ public static <T extends ByteCodeElement> ElementMatcher.Junction<T> isDeclaredBy(Class<?> type) { return isDeclaredBy(TypeDescription.ForLoadedType.of(type)); }
/** * Matches an {@link AnnotationSource} for declared annotations. * This matcher does not match inherited annotations which only exist for classes. Use * {@link net.bytebuddy.matcher.ElementMatchers#inheritsAnnotation(Class)} for matching inherited annotations. * * @param type The annotation type to match against. * @param <T> The type of the matched object. * @return A matcher that validates that an annotated element is annotated with an annotation of {@code type}. */ public static <T extends AnnotationSource> ElementMatcher.Junction<T> isAnnotatedWith(Class<? extends Annotation> type) { return isAnnotatedWith(TypeDescription.ForLoadedType.of(type)); }
argument = ((Class<?>) argument).isPrimitive() ? JavaConstant.Dynamic.ofPrimitiveType((Class<?>) argument) : TypeDescription.ForLoadedType.of((Class<?>) argument); } else if (argument instanceof TypeDescription && ((TypeDescription) argument).isPrimitive()) { argument = JavaConstant.Dynamic.ofPrimitiveType((TypeDescription) argument); } else if (JavaType.METHOD_HANDLE.getTypeStub().isInstance(argument)) { argument = JavaConstant.MethodHandle.ofLoaded(argument); } else if (JavaType.METHOD_TYPE.getTypeStub().isInstance(argument)) { argument = JavaConstant.MethodType.ofLoaded(argument);
return setsValue(new TextConstant((String) value), String.class); } else if (type == Class.class) { return setsValue(ClassConstant.of(TypeDescription.ForLoadedType.of((Class<?>) value)), Class.class); } else if (type == Boolean.class) { return setsValue(IntegerConstant.forValue((Boolean) value), boolean.class); } else if (type == Double.class) { return setsValue(DoubleConstant.forValue((Double) value), double.class); } else if (JavaType.METHOD_HANDLE.getTypeStub().isAssignableFrom(type)) { return setsValue(new JavaConstantValue(JavaConstant.MethodHandle.ofLoaded(value)), type); } else if (JavaType.METHOD_TYPE.getTypeStub().represents(type)) { return setsValue(new JavaConstantValue(JavaConstant.MethodType.ofLoaded(value)), type); } else {
/** * Matches any type description that is a subtype of the given type. * * @param type The type to be checked for being a subtype of the matched type. * @param <T> The type of the matched object. * @return A matcher that matches any type description that represents a sub type of the given type. */ public static <T extends TypeDescription> ElementMatcher.Junction<T> isSubTypeOf(Class<?> type) { return isSubTypeOf(TypeDescription.ForLoadedType.of(type)); }