Search in sources :

Example 1 with Modifier

use of java.lang.reflect.Modifier in project LanternServer by LanternPowered.

the class FieldAccessFactory method createSetter.

/**
 * Creates a setter {@link BiConsumer} for the given {@link Field}.
 *
 * @param field The field
 * @param <T> The target object type
 * @param <V> The field value type
 * @return The bi consumer
 */
public static <T, V> BiConsumer<T, V> createSetter(Field field) {
    checkNotNull(field, "field");
    field.setAccessible(true);
    boolean isFinal = Modifier.isFinal(field.getModifiers());
    // Better check is somebody changed the final modifier already
    if (!isFinal) {
        final Field[] fields = field.getDeclaringClass().getDeclaredFields();
        boolean isFound = false;
        for (Field field1 : fields) {
            // The same signature, now check if somebody tinkered with the field
            if (field.getName().equals(field1.getName()) && field.getType().equals(field1.getType())) {
                isFinal = Modifier.isFinal(field1.getModifiers());
                isFound = true;
                break;
            }
        }
        if (!isFound) {
            throw new IllegalStateException("Something funky happened with: " + field.getName());
        }
    } else {
        try {
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }
    // Final fields don't allow direct access, so MethodHandles will do the trick.
    if (isFinal) {
        try {
            final MethodHandle methodHandle = MethodHandleMagic.trustedLookup().in(field.getDeclaringClass()).unreflectSetter(field).asType(setterMethodType);
            return (a, b) -> {
                try {
                    methodHandle.invokeExact(a, b);
                } catch (Throwable throwable) {
                    throw new IllegalStateException(throwable);
                }
            };
        } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }
    final ClassWriter cw = new ClassWriter(0);
    final String className = field.getName().replace('.', '/') + "$$LanternSetter$" + setterCounter.incrementAndGet();
    cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, className, "Ljava/lang/Object;Ljava/util/function/BiConsumer<Ljava/lang/Object;Ljava/lang/Object;>;", "java/lang/Object", new String[] { "java/util/function/BiConsumer" });
    // Add a empty constructor
    BytecodeUtils.visitEmptyConstructor(cw);
    // Generate the apply method
    final MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "accept", "(Ljava/lang/Object;Ljava/lang/Object;)V", null, null);
    mv.visitCode();
    final String descriptor = Type.getDescriptor(field.getType());
    final String targetName = Type.getInternalName(field.getDeclaringClass());
    final boolean isStatic = Modifier.isStatic(field.getModifiers());
    if (!isStatic) {
        // Load the target parameter
        mv.visitVarInsn(ALOAD, 1);
        // Cast it
        mv.visitTypeInsn(CHECKCAST, targetName);
    }
    // Load the value parameter
    mv.visitVarInsn(ALOAD, 2);
    // Unbox the values in case they are primitives, otherwise cast
    GeneratorUtils.visitUnboxingMethod(mv, Type.getType(field.getType()));
    // Put the value into the field
    if (isStatic) {
        mv.visitFieldInsn(PUTSTATIC, targetName, field.getName(), descriptor);
    } else {
        mv.visitFieldInsn(PUTFIELD, targetName, field.getName(), descriptor);
    }
    // Return
    mv.visitInsn(RETURN);
    mv.visitMaxs(2, 3);
    mv.visitEnd();
    // Finish class generation
    cw.visitEnd();
    // Define the class and create a function instance
    final MethodHandles.Lookup lookup = MethodHandleMagic.trustedLookup().in(field.getDeclaringClass());
    final Class<?> functionClass = MethodHandleMagic.defineNestmateClass(lookup, cw.toByteArray());
    try {
        return (BiConsumer<T, V>) functionClass.newInstance();
    } catch (Exception e) {
        throw new IllegalStateException("Something went wrong!", e);
    }
}
Also used : ClassWriter(org.objectweb.asm.ClassWriter) MethodHandle(java.lang.invoke.MethodHandle) MethodVisitor(org.objectweb.asm.MethodVisitor) ACC_SUPER(org.objectweb.asm.Opcodes.ACC_SUPER) GETSTATIC(org.objectweb.asm.Opcodes.GETSTATIC) GeneratorUtils(org.spongepowered.api.util.generator.GeneratorUtils) V1_8(org.objectweb.asm.Opcodes.V1_8) Type(org.objectweb.asm.Type) Function(java.util.function.Function) Supplier(java.util.function.Supplier) PUTFIELD(org.objectweb.asm.Opcodes.PUTFIELD) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BiConsumer(java.util.function.BiConsumer) CHECKCAST(org.objectweb.asm.Opcodes.CHECKCAST) MethodHandles(java.lang.invoke.MethodHandles) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Field(java.lang.reflect.Field) Preconditions.checkState(com.google.common.base.Preconditions.checkState) GETFIELD(org.objectweb.asm.Opcodes.GETFIELD) Consumer(java.util.function.Consumer) MethodType(java.lang.invoke.MethodType) RETURN(org.objectweb.asm.Opcodes.RETURN) ACC_PUBLIC(org.objectweb.asm.Opcodes.ACC_PUBLIC) PUTSTATIC(org.objectweb.asm.Opcodes.PUTSTATIC) Modifier(java.lang.reflect.Modifier) ARETURN(org.objectweb.asm.Opcodes.ARETURN) ALOAD(org.objectweb.asm.Opcodes.ALOAD) ClassWriter(org.objectweb.asm.ClassWriter) MethodVisitor(org.objectweb.asm.MethodVisitor) Field(java.lang.reflect.Field) MethodHandles(java.lang.invoke.MethodHandles) BiConsumer(java.util.function.BiConsumer) MethodHandle(java.lang.invoke.MethodHandle)

Example 2 with Modifier

use of java.lang.reflect.Modifier in project flow by vaadin.

the class SchemaGenerator method getFieldsAndOptionalMap.

/**
 * Because it's not possible to check the `transient` modifier and
 * annotation of a field using JavaParser API. We need this method to
 * reflect the type and get those information from the reflected object.
 *
 * @param type
 *            type of the class to get fields information
 * @return set of fields' name that we should generate.
 */
private Map<String, Boolean> getFieldsAndOptionalMap(GeneratorType type) {
    ResolvedReferenceType resolvedReferenceType = type.asResolvedType().asReferenceType();
    Optional<ResolvedReferenceTypeDeclaration> typeDeclaration = resolvedReferenceType.getTypeDeclaration();
    if (!typeDeclaration.filter(td -> td.isClass() && !td.isAnonymousClass()).isPresent()) {
        return Collections.emptyMap();
    }
    HashMap<String, Boolean> validFields = new HashMap<>();
    try {
        Class<?> aClass = openApiObjectGenerator.getClassFromReflection(type);
        Arrays.stream(aClass.getDeclaredFields()).filter(field -> {
            int modifiers = field.getModifiers();
            return !Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && !field.isAnnotationPresent(JsonIgnore.class);
        }).forEach(field -> validFields.put(field.getName(), !ExplicitNullableTypeChecker.isRequired(field)));
    } catch (ClassNotFoundException e) {
        String message = String.format("Can't get list of fields from class '%s'." + "Please make sure that class '%s' is in your project's compile classpath. " + "As the result, the generated TypeScript file will be empty.", resolvedReferenceType.getQualifiedName(), resolvedReferenceType.getQualifiedName());
        getLogger().info(message);
        getLogger().debug(message, e);
    }
    return validFields;
}
Also used : Arrays(java.util.Arrays) AnnotationExpr(com.github.javaparser.ast.expr.AnnotationExpr) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) LinkedHashMap(java.util.LinkedHashMap) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) Type(com.github.javaparser.ast.type.Type) ResolvedFieldDeclaration(com.github.javaparser.resolution.declarations.ResolvedFieldDeclaration) Map(java.util.Map) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) Schema(io.swagger.v3.oas.models.media.Schema) LinkedHashSet(java.util.LinkedHashSet) Logger(org.slf4j.Logger) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) Set(java.util.Set) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) Collectors(java.util.stream.Collectors) List(java.util.List) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) StringSchema(io.swagger.v3.oas.models.media.StringSchema) ResolvedEnumConstantDeclaration(com.github.javaparser.resolution.declarations.ResolvedEnumConstantDeclaration) Modifier(java.lang.reflect.Modifier) Optional(java.util.Optional) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) ExplicitNullableTypeChecker(dev.hilla.ExplicitNullableTypeChecker) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 3 with Modifier

use of java.lang.reflect.Modifier in project flink by apache.

the class UserDefinedFunctionHelper method validateImplementationMethod.

/**
 * Validates an implementation method such as {@code eval()} or {@code accumulate()}.
 */
private static void validateImplementationMethod(Class<? extends UserDefinedFunction> clazz, boolean rejectStatic, boolean isOptional, String... methodNameOptions) {
    final Set<String> nameSet = new HashSet<>(Arrays.asList(methodNameOptions));
    final List<Method> methods = getAllDeclaredMethods(clazz);
    boolean found = false;
    for (Method method : methods) {
        if (!nameSet.contains(method.getName())) {
            continue;
        }
        found = true;
        final int modifier = method.getModifiers();
        if (!Modifier.isPublic(modifier)) {
            throw new ValidationException(String.format("Method '%s' of function class '%s' is not public.", method.getName(), clazz.getName()));
        }
        if (Modifier.isAbstract(modifier)) {
            throw new ValidationException(String.format("Method '%s' of function class '%s' must not be abstract.", method.getName(), clazz.getName()));
        }
        if (rejectStatic && Modifier.isStatic(modifier)) {
            throw new ValidationException(String.format("Method '%s' of function class '%s' must not be static.", method.getName(), clazz.getName()));
        }
    }
    if (!found && !isOptional) {
        throw new ValidationException(String.format("Function class '%s' does not implement a method named %s.", clazz.getName(), nameSet.stream().map(s -> "'" + s + "'").collect(Collectors.joining(" or "))));
    }
}
Also used : DataType(org.apache.flink.table.types.DataType) Arrays(java.util.Arrays) SpecializedContext(org.apache.flink.table.functions.SpecializedFunction.SpecializedContext) PipelineOptions(org.apache.flink.configuration.PipelineOptions) PythonFunctionUtils(org.apache.flink.table.functions.python.utils.PythonFunctionUtils) HashSet(java.util.HashSet) InstantiationUtil(org.apache.flink.util.InstantiationUtil) ReadableConfig(org.apache.flink.configuration.ReadableConfig) TypeInformation(org.apache.flink.api.common.typeinfo.TypeInformation) Method(java.lang.reflect.Method) Nullable(javax.annotation.Nullable) Preconditions.checkState(org.apache.flink.util.Preconditions.checkState) TableException(org.apache.flink.table.api.TableException) Set(java.util.Set) TypeExtractionUtils.getAllDeclaredMethods(org.apache.flink.api.java.typeutils.TypeExtractionUtils.getAllDeclaredMethods) Field(java.lang.reflect.Field) Collectors(java.util.stream.Collectors) CallContext(org.apache.flink.table.types.inference.CallContext) List(java.util.List) TypeExtractor(org.apache.flink.api.java.typeutils.TypeExtractor) CatalogFunction(org.apache.flink.table.catalog.CatalogFunction) ClosureCleanerLevel(org.apache.flink.api.common.ExecutionConfig.ClosureCleanerLevel) ValidationException(org.apache.flink.table.api.ValidationException) Modifier(java.lang.reflect.Modifier) Internal(org.apache.flink.annotation.Internal) ClosureCleaner(org.apache.flink.api.java.ClosureCleaner) ExtractionUtils(org.apache.flink.table.types.extraction.ExtractionUtils) ValidationException(org.apache.flink.table.api.ValidationException) Method(java.lang.reflect.Method) HashSet(java.util.HashSet)

Aggregations

Modifier (java.lang.reflect.Modifier)3 Field (java.lang.reflect.Field)2 Arrays (java.util.Arrays)2 List (java.util.List)2 Set (java.util.Set)2 Collectors (java.util.stream.Collectors)2 JsonIgnore (com.fasterxml.jackson.annotation.JsonIgnore)1 FieldDeclaration (com.github.javaparser.ast.body.FieldDeclaration)1 TypeDeclaration (com.github.javaparser.ast.body.TypeDeclaration)1 AnnotationExpr (com.github.javaparser.ast.expr.AnnotationExpr)1 Type (com.github.javaparser.ast.type.Type)1 ResolvedEnumConstantDeclaration (com.github.javaparser.resolution.declarations.ResolvedEnumConstantDeclaration)1 ResolvedFieldDeclaration (com.github.javaparser.resolution.declarations.ResolvedFieldDeclaration)1 ResolvedReferenceTypeDeclaration (com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration)1 ResolvedReferenceType (com.github.javaparser.resolution.types.ResolvedReferenceType)1 ResolvedType (com.github.javaparser.resolution.types.ResolvedType)1 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)1 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1 ExplicitNullableTypeChecker (dev.hilla.ExplicitNullableTypeChecker)1 ComposedSchema (io.swagger.v3.oas.models.media.ComposedSchema)1