Java Code Examples for net.bytebuddy.description.type.TypeDescription#isAssignableTo()

The following examples show how to use net.bytebuddy.description.type.TypeDescription#isAssignableTo() . 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: ClassWriterStrategy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected String getCommonSuperClass(String leftTypeName, String rightTypeName) {
    TypeDescription leftType = typePool.describe(leftTypeName.replace('/', '.')).resolve();
    TypeDescription rightType = typePool.describe(rightTypeName.replace('/', '.')).resolve();
    if (leftType.isAssignableFrom(rightType)) {
        return leftType.getInternalName();
    } else if (leftType.isAssignableTo(rightType)) {
        return rightType.getInternalName();
    } else if (leftType.isInterface() || rightType.isInterface()) {
        return TypeDescription.OBJECT.getInternalName();
    } else {
        do {
            leftType = leftType.getSuperClass().asErasure();
        } while (!leftType.isAssignableFrom(rightType));
        return leftType.getInternalName();
    }
}
 
Example 2
Source File: MethodDescription.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean isDefaultValue(AnnotationValue<?, ?> annotationValue) {
    if (!isDefaultValue()) {
        return false;
    }
    TypeDescription returnType = getReturnType().asErasure();
    Object value = annotationValue.resolve();
    return (returnType.represents(boolean.class) && value instanceof Boolean)
            || (returnType.represents(byte.class) && value instanceof Byte)
            || (returnType.represents(char.class) && value instanceof Character)
            || (returnType.represents(short.class) && value instanceof Short)
            || (returnType.represents(int.class) && value instanceof Integer)
            || (returnType.represents(long.class) && value instanceof Long)
            || (returnType.represents(float.class) && value instanceof Float)
            || (returnType.represents(double.class) && value instanceof Double)
            || (returnType.represents(String.class) && value instanceof String)
            || (returnType.isAssignableTo(Enum.class) && value instanceof EnumerationDescription && isEnumerationType(returnType, (EnumerationDescription) value))
            || (returnType.isAssignableTo(Annotation.class) && value instanceof AnnotationDescription && isAnnotationType(returnType, (AnnotationDescription) value))
            || (returnType.represents(Class.class) && value instanceof TypeDescription)
            || (returnType.represents(boolean[].class) && value instanceof boolean[])
            || (returnType.represents(byte[].class) && value instanceof byte[])
            || (returnType.represents(char[].class) && value instanceof char[])
            || (returnType.represents(short[].class) && value instanceof short[])
            || (returnType.represents(int[].class) && value instanceof int[])
            || (returnType.represents(long[].class) && value instanceof long[])
            || (returnType.represents(float[].class) && value instanceof float[])
            || (returnType.represents(double[].class) && value instanceof double[])
            || (returnType.represents(String[].class) && value instanceof String[])
            || (returnType.isAssignableTo(Enum[].class) && value instanceof EnumerationDescription[] && isEnumerationType(returnType.getComponentType(), (EnumerationDescription[]) value))
            || (returnType.isAssignableTo(Annotation[].class) && value instanceof AnnotationDescription[] && isAnnotationType(returnType.getComponentType(), (AnnotationDescription[]) value))
            || (returnType.represents(Class[].class) && value instanceof TypeDescription[]);
}
 
Example 3
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public FieldDescription resolve(TypeDescription instrumentedType) {
    if (!fieldDescription.isStatic() && !instrumentedType.isAssignableTo(fieldDescription.getType().asErasure())) {
        throw new IllegalStateException("Cannot access " + fieldDescription + " from " + instrumentedType);
    }
    return fieldDescription;
}
 
Example 4
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public TerminationHandler make(TypeDescription instrumentedType) {
    if (!fieldDescription.isStatic() && !instrumentedType.isAssignableTo(fieldDescription.getDeclaringType().asErasure())) {
        throw new IllegalStateException("Cannot set " + fieldDescription + " from " + instrumentedType);
    } else if (!fieldDescription.isAccessibleTo(instrumentedType)) {
        throw new IllegalStateException("Cannot access " + fieldDescription + " from " + instrumentedType);
    }
    return new FieldSetting(fieldDescription);
}
 
Example 5
Source File: FieldAccessor.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Prepared prepare(TypeDescription instrumentedType) {
    if (!fieldDescription.isStatic() && !instrumentedType.isAssignableTo(fieldDescription.getDeclaringType().asErasure())) {
        throw new IllegalStateException(fieldDescription + " is not declared by " + instrumentedType);
    } else if (!fieldDescription.isAccessibleTo(instrumentedType)) {
        throw new IllegalStateException("Cannot access " + fieldDescription + " from " + instrumentedType);
    }
    return this;
}
 
Example 6
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Resolved resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Assigner.Typing typing) {
    if (instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot get this instance from static method: " + instrumentedMethod);
    } else if (!instrumentedType.isAssignableTo(typeDescription)) {
        throw new IllegalStateException(instrumentedType + " is not assignable to " + instrumentedType);
    }
    return new Resolved.Simple(MethodVariableAccess.loadThis(), typeDescription);
}
 
Example 7
Source File: MethodGraph.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Combines the two given stores.
 *
 * @param left  The left store to be combined.
 * @param right The right store to be combined.
 * @param <W>   The type of the harmonized key of both stores.
 * @return An entry representing the combination of both stores.
 */
private static <W> Entry<W> combine(Entry<W> left, Entry<W> right) {
    Set<MethodDescription> leftMethods = left.getCandidates(), rightMethods = right.getCandidates();
    LinkedHashSet<MethodDescription> combined = new LinkedHashSet<MethodDescription>();
    combined.addAll(leftMethods);
    combined.addAll(rightMethods);
    for (MethodDescription leftMethod : leftMethods) {
        TypeDescription leftType = leftMethod.getDeclaringType().asErasure();
        for (MethodDescription rightMethod : rightMethods) {
            TypeDescription rightType = rightMethod.getDeclaringType().asErasure();
            if (leftType.equals(rightType)) {
                break;
            } else if (leftType.isAssignableTo(rightType)) {
                combined.remove(rightMethod);
                break;
            } else if (leftType.isAssignableFrom(rightType)) {
                combined.remove(leftMethod);
                break;
            }
        }
    }
    Key.Harmonized<W> key = left.getKey().combineWith(right.getKey());
    Visibility visibility = left.getVisibility().expandTo(right.getVisibility());
    return combined.size() == 1
            ? new Entry.Resolved<W>(key, combined.iterator().next(), visibility, Entry.Resolved.NOT_MADE_VISIBLE)
            : new Entry.Ambiguous<W>(key, combined, visibility);
}
 
Example 8
Source File: BiDirectionalAssociationHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
static Implementation wrap(
		TypeDescription managedCtClass,
		ByteBuddyEnhancementContext enhancementContext,
		FieldDescription persistentField,
		Implementation implementation) {
	if ( !enhancementContext.doBiDirectionalAssociationManagement( persistentField ) ) {
		return implementation;
	}

	TypeDescription targetEntity = getTargetEntityClass( managedCtClass, persistentField );
	if ( targetEntity == null ) {
		return implementation;
	}
	String mappedBy = getMappedBy( persistentField, targetEntity, enhancementContext );
	if ( mappedBy == null || mappedBy.isEmpty() ) {
		log.infof(
				"Could not find bi-directional association for field [%s#%s]",
				managedCtClass.getName(),
				persistentField.getName()
		);
		return implementation;
	}

	TypeDescription targetType = FieldLocator.ForClassHierarchy.Factory.INSTANCE.make( targetEntity )
			.locate( mappedBy )
			.getField()
			.getType()
			.asErasure();

	if ( EnhancerImpl.isAnnotationPresent( persistentField, OneToOne.class ) ) {
		implementation = Advice.withCustomMapping()
				.bind( CodeTemplates.FieldValue.class, persistentField )
				.bind( CodeTemplates.MappedBy.class, mappedBy )
				.to( CodeTemplates.OneToOneHandler.class )
				.wrap( implementation );
	}

	if ( EnhancerImpl.isAnnotationPresent( persistentField, OneToMany.class ) ) {
		implementation = Advice.withCustomMapping()
				.bind( CodeTemplates.FieldValue.class, persistentField )
				.bind( CodeTemplates.MappedBy.class, mappedBy )
				.to( persistentField.getType().asErasure().isAssignableTo( Map.class )
							? CodeTemplates.OneToManyOnMapHandler.class
							: CodeTemplates.OneToManyOnCollectionHandler.class )
				.wrap( implementation );
	}

	if ( EnhancerImpl.isAnnotationPresent( persistentField, ManyToOne.class ) ) {
		implementation = Advice.withCustomMapping()
				.bind( CodeTemplates.FieldValue.class, persistentField )
				.bind( CodeTemplates.MappedBy.class, mappedBy )
				.to( CodeTemplates.ManyToOneHandler.class )
				.wrap( implementation );
	}

	if ( EnhancerImpl.isAnnotationPresent( persistentField, ManyToMany.class ) ) {

		if ( persistentField.getType().asErasure().isAssignableTo( Map.class ) || targetType.isAssignableTo( Map.class ) ) {
			log.infof(
					"Bi-directional association for field [%s#%s] not managed: @ManyToMany in java.util.Map attribute not supported ",
					managedCtClass.getName(),
					persistentField.getName()
			);
			return implementation;
		}

		implementation = Advice.withCustomMapping()
				.bind( CodeTemplates.FieldValue.class, persistentField )
				.bind( CodeTemplates.MappedBy.class, mappedBy )
				.to( CodeTemplates.ManyToManyHandler.class )
				.wrap( implementation );
	}

	return new BiDirectionalAssociationHandler( implementation, targetEntity, targetType, mappedBy );
}
 
Example 9
Source File: JavaConstant.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * Represents a constant that is resolved by invoking a {@code static} factory method or a constructor.
 *
 * @param methodDescription The method or constructor to invoke to create the represented constant value.
 * @param constants         The constant values passed to the bootstrap method. Values can be represented either
 *                          as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
 *                          {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
 * @return A dynamic constant that is resolved by the supplied factory method or constructor.
 */
public static Dynamic ofInvocation(MethodDescription.InDefinedShape methodDescription, List<?> constants) {
    if (!methodDescription.isConstructor() && methodDescription.getReturnType().represents(void.class)) {
        throw new IllegalArgumentException("Bootstrap method is no constructor or non-void static factory: " + methodDescription);
    } else if (methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) != constants.size()) {
        throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription);
    }
    List<Object> arguments = new ArrayList<Object>(constants.size());
    arguments.add(new Handle(methodDescription.isConstructor() ? Opcodes.H_NEWINVOKESPECIAL : Opcodes.H_INVOKESTATIC,
            methodDescription.getDeclaringType().getInternalName(),
            methodDescription.getInternalName(),
            methodDescription.getDescriptor(),
            false));
    Iterator<TypeDescription> iterator = (methodDescription.isStatic() || methodDescription.isConstructor()
            ? methodDescription.getParameters().asTypeList().asErasures()
            : CompoundList.of(methodDescription.getDeclaringType(), methodDescription.getParameters().asTypeList().asErasures())).iterator();
    for (Object constant : constants) {
        TypeDescription typeDescription;
        if (constant instanceof JavaConstant) {
            arguments.add(((JavaConstant) constant).asConstantPoolValue());
            typeDescription = ((JavaConstant) constant).getType();
        } else if (constant instanceof TypeDescription) {
            arguments.add(Type.getType(((TypeDescription) constant).getDescriptor()));
            typeDescription = TypeDescription.CLASS;
        } else {
            arguments.add(constant);
            typeDescription = TypeDescription.ForLoadedType.of(constant.getClass()).asUnboxed();
            if (JavaType.METHOD_TYPE.isInstance(constant) || JavaType.METHOD_HANDLE.isInstance(constant)) {
                throw new IllegalArgumentException("Must be represented as a JavaConstant instance: " + constant);
            } else if (constant instanceof Class<?>) {
                throw new IllegalArgumentException("Must be represented as a TypeDescription instance: " + constant);
            } else if (!typeDescription.isCompileTimeConstant()) {
                throw new IllegalArgumentException("Not a compile-time constant: " + constant);
            }
        }
        if (!typeDescription.isAssignableTo(iterator.next())) {
            throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription);
        }
    }
    return new Dynamic(new ConstantDynamic("invoke",
            (methodDescription.isConstructor()
                    ? methodDescription.getDeclaringType()
                    : methodDescription.getReturnType().asErasure()).getDescriptor(),
            new Handle(Opcodes.H_INVOKESTATIC,
                    CONSTANT_BOOTSTRAPS,
                    "invoke",
                    "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/invoke/MethodHandle;[Ljava/lang/Object;)Ljava/lang/Object;",
                    false),
            arguments.toArray()), methodDescription.isConstructor() ? methodDescription.getDeclaringType() : methodDescription.getReturnType().asErasure());
}
 
Example 10
Source File: ToStringMethod.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * Resolves an appropriate value resolver for a given type.
 *
 * @param typeDescription The type for which to resolve a value resolver.
 * @return An appropriate stack manipulation.
 */
protected static StackManipulation of(TypeDescription typeDescription) {
    if (typeDescription.represents(boolean.class)) {
        return BOOLEAN;
    } else if (typeDescription.represents(char.class)) {
        return CHARACTER;
    } else if (typeDescription.represents(byte.class)
            || typeDescription.represents(short.class)
            || typeDescription.represents(int.class)) {
        return INTEGER;
    } else if (typeDescription.represents(long.class)) {
        return LONG;
    } else if (typeDescription.represents(float.class)) {
        return FLOAT;
    } else if (typeDescription.represents(double.class)) {
        return DOUBLE;
    } else if (typeDescription.represents(String.class)) {
        return STRING;
    } else if (typeDescription.isAssignableTo(CharSequence.class)) {
        return CHARACTER_SEQUENCE;
    } else if (typeDescription.represents(boolean[].class)) {
        return BOOLEAN_ARRAY;
    } else if (typeDescription.represents(byte[].class)) {
        return BYTE_ARRAY;
    } else if (typeDescription.represents(short[].class)) {
        return SHORT_ARRAY;
    } else if (typeDescription.represents(char[].class)) {
        return CHARACTER_ARRAY;
    } else if (typeDescription.represents(int[].class)) {
        return INTEGER_ARRAY;
    } else if (typeDescription.represents(long[].class)) {
        return LONG_ARRAY;
    } else if (typeDescription.represents(float[].class)) {
        return FLOAT_ARRAY;
    } else if (typeDescription.represents(double[].class)) {
        return DOUBLE_ARRAY;
    } else if (typeDescription.isArray()) {
        return typeDescription.getComponentType().isArray()
                ? NESTED_ARRAY
                : REFERENCE_ARRAY;
    } else {
        return OBJECT;
    }
}
 
Example 11
Source File: ExceptionMethod.java    From byte-buddy with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an implementation that creates a new instance of the given {@link Throwable} type on each method invocation
 * which is then thrown immediately. For this to be possible, the given type must define a default constructor
 * which is visible from the instrumented type.
 *
 * @param throwableType The type of the {@link Throwable}.
 * @return An implementation that will throw an instance of the {@link Throwable} on each method invocation of the
 * instrumented methods.
 */
public static Implementation throwing(TypeDescription throwableType) {
    if (!throwableType.isAssignableTo(Throwable.class)) {
        throw new IllegalArgumentException(throwableType + " does not extend throwable");
    }
    return new ExceptionMethod(new ConstructionDelegate.ForDefaultConstructor(throwableType));
}
 
Example 12
Source File: ExceptionMethod.java    From byte-buddy with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an implementation that creates a new instance of the given {@link Throwable} type on each method
 * invocation which is then thrown immediately. For this to be possible, the given type must define a
 * constructor that takes a single {@link java.lang.String} as its argument.
 *
 * @param throwableType The type of the {@link Throwable}.
 * @param message       The string that is handed to the constructor. Usually an exception message.
 * @return An implementation that will throw an instance of the {@link Throwable} on each method invocation
 * of the instrumented methods.
 */
public static Implementation throwing(TypeDescription throwableType, String message) {
    if (!throwableType.isAssignableTo(Throwable.class)) {
        throw new IllegalArgumentException(throwableType + " does not extend throwable");
    }
    return new ExceptionMethod(new ConstructionDelegate.ForStringConstructor(throwableType, message));
}
 
Example 13
Source File: ElementMatchers.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Matches a {@link MethodDescription} by its capability to throw a given
 * checked exception. For specifying a non-checked exception, any method is matched.
 *
 * @param exceptionType The type of the exception that should be declared by the method to be matched.
 * @param <T>           The type of the matched object.
 * @return A matcher that matches a method description by its declaration of throwing a checked exception.
 */
public static <T extends MethodDescription> ElementMatcher.Junction<T> canThrow(TypeDescription exceptionType) {
    return exceptionType.isAssignableTo(RuntimeException.class) || exceptionType.isAssignableTo(Error.class)
            ? new BooleanMatcher<T>(true)
            : ElementMatchers.<T>declaresGenericException(new CollectionItemMatcher<TypeDescription.Generic>(erasure(isSuperTypeOf(exceptionType))));
}
 
Example 14
Source File: ElementMatchers.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Matches a method that declares the given generic exception type as a (erased) exception type.
 *
 * @param exceptionType The exception type that is matched.
 * @param <T>           The type of the matched object.
 * @return A matcher that matches any method that exactly matches the provided exception.
 */
public static <T extends MethodDescription> ElementMatcher.Junction<T> declaresException(TypeDescription exceptionType) {
    return exceptionType.isAssignableTo(Throwable.class)
            ? ElementMatchers.<T>declaresGenericException(new CollectionItemMatcher<TypeDescription.Generic>(erasure(exceptionType)))
            : new BooleanMatcher<T>(false);
}