Example usage for java.lang.reflect Modifier isStatic

List of usage examples for java.lang.reflect Modifier isStatic

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isStatic.

Prototype

public static boolean isStatic(int mod) 

Source Link

Document

Return true if the integer argument includes the static modifier, false otherwise.

Usage

From source file:org.apache.lens.api.jaxb.YAMLToStringStrategy.java

@Override
protected StringBuilder appendInternal(ObjectLocator locator, StringBuilder stringBuilder, Object value) {
    insideArray = insideArrayStack.peek();
    insideArrayStack.push(false);/*from   ww  w. j  av  a2  s  .  c o  m*/
    try {
        if (value instanceof String && ((String) value).isEmpty()) {
            appendNullText(stringBuilder);
            return stringBuilder;
        }
        if (!canBeInlinedWithOtherArrayElements(value)) {
            appendNewLine(stringBuilder);
        }
        if (value instanceof Map) {
            indentationValue++;
            for (Object key : ((Map) value).keySet()) {
                appendNewLine(indent(stringBuilder).append(key).append(": ").append(((Map) value).get(key)));
            }
            indentationValue--;
            return stringBuilder;
        }
        if (value instanceof XProperty || value instanceof XPartSpecElement
                || value instanceof XTimePartSpecElement || value instanceof ResultColumn) {
            removeLastArrayStart(stringBuilder);
            if (value instanceof ResultColumn) {
                ResultColumn column = (ResultColumn) value;
                indent(stringBuilder).append(column.getName()).append(": ").append(column.getType());
            }
            if (value instanceof XProperty) {
                XProperty property = (XProperty) value;
                indent(stringBuilder).append(property.getName()).append(": ").append(property.getValue());
            }
            if (value instanceof XPartSpecElement) {
                XPartSpecElement partSpecElement = (XPartSpecElement) value;
                indent(stringBuilder).append(partSpecElement.getKey()).append(": ")
                        .append(partSpecElement.getValue());
            }
            if (value instanceof XTimePartSpecElement) {
                XTimePartSpecElement partSpecElement = (XTimePartSpecElement) value;
                indent(stringBuilder).append(partSpecElement.getKey()).append(": ")
                        .append(partSpecElement.getValue());
            }
            return appendNewLine(stringBuilder);
        }

        if (value instanceof XJoinEdge) {
            XJoinEdge edge = (XJoinEdge) value;
            XTableReference from = edge.getFrom();
            XTableReference to = edge.getTo();
            stringBuilder.setLength(stringBuilder.length() - 2);
            stringBuilder.append(from.getTable()).append(".").append(from.getColumn())
                    .append(from.isMapsToMany() ? "(many)" : "").append("=").append(to.getTable()).append(".")
                    .append(to.getColumn()).append(to.isMapsToMany() ? "(many)" : "");
            return appendNewLine(stringBuilder);
        }
        NameableContext context = getNameableContext(value);
        if (context != null) {
            String heading = context.getHeading();
            if (isBlank(heading)) {
                heading = "-";
            }
            if (insideArray) {
                stringBuilder.setLength(stringBuilder.length() - 2);
            }
            String details = context.getDetails();
            stringBuilder.append(heading);
            if (details.charAt(0) != '\n') {
                stringBuilder.append(" ");
            }
            stringBuilder.append(details);
            return appendNewLine(stringBuilder);
        }
        // some other way of getting heading
        if (value instanceof Collection) {
            Collection collection = (Collection) value;
            // try inline
            StringBuilder allElements = super.appendInternal(locator, new StringBuilder(), value);
            if (collection.size() != 0 && canBeInlinedWithOtherArrayElements((collection.iterator().next()))
                    && allElements.length() < 120) {
                stringBuilder.setLength(stringBuilder.length() - 1);
                String sep = " ";
                for (Object singleElement : collection) {
                    stringBuilder.append(sep);
                    appendInternal(locator, stringBuilder, singleElement);
                    sep = ", ";
                }
                return stringBuilder;
            } else {
                return stringBuilder.append(allElements);
            }
        }
        // If this class is just a wrapper over a another object
        Field[] fields = value.getClass().getDeclaredFields();
        int nonStaticFields = 0;
        String fieldName = null;
        for (Field field : fields) {
            if (!Modifier.isStatic(field.getModifiers())) {
                nonStaticFields++;
                fieldName = field.getName();
            }
        }
        if (nonStaticFields == 1) {
            Class<?> claz = value.getClass();
            String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            try {
                Object wrappedValue = claz.getDeclaredMethod(getterName).invoke(value);
                return appendNewLine(appendInternal(locator, stringBuilder, wrappedValue));
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                log.trace("getter access failed for {}#{}. Going the usual way", claz.getName(), getterName, e);
            }
        }
        return super.appendInternal(locator, stringBuilder, value);
    } finally {
        insideArrayStack.pop();
    }
}

From source file:me.rojo8399.placeholderapi.impl.utils.TypeUtils.java

@SuppressWarnings("unchecked")
public static <T> Optional<T> tryCast(Object val, final Class<T> expected) {
    if (val == null) {
        return Optional.empty();
    }/*from w w  w  .ja v  a2 s. c  om*/
    if (expected == null) {
        throw new IllegalArgumentException("Must provide an expected class!");
    }
    if (val instanceof BaseValue<?> && !BaseValue.class.isAssignableFrom(expected)) {
        return tryCast(((BaseValue<?>) val).get(), expected);
    }
    if (val instanceof Supplier) {
        Supplier<?> fun = (Supplier<?>) val;
        return tryCast(fun.get(), expected);
    }
    if (Text.class.isAssignableFrom(expected)) {
        if (val instanceof Text) {
            return TypeUtils.tryOptional(() -> expected.cast(val));
        } else {
            if (val instanceof ItemStack) {
                return TypeUtils.tryOptional(() -> expected.cast(TextUtils.ofItem((ItemStack) val)));
            }
            if (val instanceof Instant) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE
                        .deserialize(PlaceholderAPIPlugin.getInstance().formatter()
                                .format(LocalDateTime.ofInstant((Instant) val, ZoneId.systemDefault())))));
            }
            if (val instanceof Duration) {
                String dur = formatDuration((Duration) val);
                return TypeUtils
                        .tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(dur)));
            }
            if (val instanceof LocalDateTime) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(
                        PlaceholderAPIPlugin.getInstance().formatter().format((LocalDateTime) val))));
            }
            if (val instanceof CommandSource) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE
                        .deserialize(String.valueOf(((CommandSource) val).getName()))));
            }
            if (val.getClass().isArray()) {
                List<Text> l2 = unboxPrimitiveArray(val).stream()
                        .map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional())
                        .collect(Collectors.toList());
                return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2)));
            }
            if (val instanceof Iterable) {
                Iterable<?> l = (Iterable<?>) val;
                // should be safe cause we already checked assignability
                @SuppressWarnings("serial")
                final List<Text> l2 = new ArrayList<Object>() {
                    {
                        for (Object o : l) {
                            add(o);
                        }
                    }
                }.stream().map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional())
                        .collect(Collectors.toList());
                return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2)));
            }
            return TypeUtils.tryOptional(
                    () -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(String.valueOf(val))));
        }
    }
    if (val instanceof String) {
        if (String.class.isAssignableFrom(expected)) {
            return tryOptional(() -> expected.cast(val));
        }
        if (expected.isArray() && String.class.isAssignableFrom(expected.getComponentType())) {
            String v = (String) val;
            if (v.isEmpty()) {
                return Optional.empty();
            }
            if (!v.contains("_")) {
                return tryOptional(() -> expected.cast(new String[] { v }));
            }
            String[] x = v.split("_");
            if (x.length == 0) {
                return Optional.empty();
            }
            boolean ne = false;
            for (String s : x) {
                ne = ne || !s.isEmpty();
            }
            if (!ne) {
                return Optional.empty();
            }
            return tryOptional(() -> expected.cast(x));
        }
        if (List.class.isAssignableFrom(expected)
                && String.class.isAssignableFrom(expected.getTypeParameters()[0].getGenericDeclaration())) {
            String v = (String) val;
            if (v.isEmpty()) {
                return Optional.empty();
            }
            if (!v.contains("_")) {
                return tryOptional(() -> expected.cast(Collections.singletonList(v)));
            }
            String[] x = v.split("_");
            if (x.length == 0) {
                return Optional.empty();
            }
            boolean ne = false;
            for (String s : x) {
                ne = ne || !s.isEmpty();
            }
            if (!ne) {
                return Optional.empty();
            }
            return tryOptional(() -> expected.cast(Arrays.asList(x)));
        }
        Optional<T> opt = tryOptional(() -> convertPrimitive((String) val, expected));
        if (opt.isPresent()) {
            return opt;
        }
        opt = deserializers.entrySet().stream()
                .filter(e -> e.getKey().isSubtypeOf(expected) || e.getKey().getRawType().equals(expected))
                .map(Map.Entry::getValue).map(f -> tryOptional(() -> f.apply((String) val)))
                .flatMap(unmapOptional()).findAny().flatMap(o -> tryOptional(() -> expected.cast(o)));
        if (opt.isPresent()) {
            return opt;
        }
        try {
            // should theoretically match any string -> object conversions, such as deser

            // for now im filtering against method names as well just to avoid issues where
            // expected result is not obtained due to weird methods, might change in future
            Method method = Arrays.stream(expected.getDeclaredMethods())
                    .filter(m -> Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers()))
                    .filter(m -> Arrays.stream(m.getParameterTypes()).anyMatch(c -> c.equals(String.class)))
                    .filter(m -> m.getReturnType().equals(expected) || m.getReturnType().equals(Optional.class))
                    .filter(m -> STRING_TO_VAL_PATTERN.matcher(m.getName()).find()).findAny().get(); // error if no
            Object valout = method.invoke(null, (String) val);
            if (valout == null) {
                return Optional.empty();
            }
            if (expected.isInstance(valout)) {
                // Register a new deserializer once we confirm it works. Should prevent
                // extremely long parsing from happening multiple times.
                final MethodHandle mh = MethodHandles.publicLookup().unreflect(method);
                PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> {
                    try {
                        return expected.cast(mh.invokeExact((String) val));
                    } catch (Throwable e1) {
                        throw new RuntimeException(e1);
                    }
                });
                return tryOptional(() -> expected.cast(valout));
            }
            if (valout instanceof Optional) {
                Optional<?> valopt = (Optional<?>) valout;
                if (!valopt.isPresent()) {
                    return Optional.empty();
                }
                Object v = valopt.get();
                if (expected.isInstance(v)) {
                    // Register a new deserializer once we confirm it works. Should prevent
                    // extremely long parsing from happening multiple times.
                    final MethodHandle mh = MethodHandles.publicLookup().unreflect(method);
                    PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> {
                        try {
                            Optional<?> optx = (Optional<?>) mh.invokeExact((String) val);
                            return expected.cast(optx.get());
                        } catch (Throwable e1) {
                            throw new RuntimeException(e1);
                        }
                    });
                    return tryOptional(() -> expected.cast(v));
                } else {
                    return Optional.empty();
                }
            }
            return Optional.empty();
        } catch (Exception e) {
            // fires if no method found, if invoke throws, if something else goes wrong
            return Optional.empty();
        }
    }
    return TypeUtils.tryOptional(() -> expected.cast(val));
}

From source file:cn.webwheel.DefaultMain.java

@SuppressWarnings("unchecked")
private void autoMap(String root, String pkg, String name) {
    Class cls;/*from w  w  w  .  j a v  a 2 s.c o  m*/
    try {
        cls = Class.forName(pkg + "." + name);
    } catch (ClassNotFoundException e) {
        return;
    }
    if (cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers())) {
        return;
    }
    if (cls.isAnonymousClass() || cls.isLocalClass() || !Modifier.isPublic(cls.getModifiers())
            || Modifier.isAbstract(cls.getModifiers())) {
        return;
    }

    name = name.replace('$', '.');

    for (Method method : cls.getMethods()) {

        String pathPrefix = pkg.substring(root.length()).replace('.', '/') + '/';
        String path = pathPrefix + name + '.' + method.getName();

        Action action = getAction(cls, method);
        if (action == null)
            continue;

        if (!action.value().isEmpty()) {
            if (action.value().startsWith("?")) {
                path = path + action.value();
            } else if (action.value().startsWith(".")) {
                path = pathPrefix + name + action.value();
            } else if (!action.value().startsWith("/")) {
                path = pathPrefix + action.value();
            } else {
                path = action.value();
            }
        }
        ActionBinder binder = map(path);
        if (!action.rest().isEmpty()) {
            String rest = action.rest();
            if (!rest.startsWith("/"))
                rest = pathPrefix + rest;
            binder = binder.rest(rest);
        }
        SetterConfig cfg = binder.with(cls, method);
        if (!action.charset().isEmpty()) {
            cfg = cfg.setCharset(action.charset());
        }
        if (action.fileUploadFileSizeMax() != 0) {
            cfg = cfg.setFileUploadFileSizeMax(action.fileUploadFileSizeMax());
        }
        if (action.fileUploadSizeMax() != 0) {
            cfg.setFileUploadSizeMax(action.fileUploadSizeMax());
        }
        if (action.setterPolicy() != SetterPolicy.Auto) {
            cfg.setSetterPolicy(action.setterPolicy());
        }
    }
}

From source file:cern.c2mon.shared.common.datatag.address.impl.HardwareAddressImpl.java

/**
 * The two addresses are considered equals if they're of the same type and all their non-static attributes are equal
 *//*w  w w. jav a  2  s. com*/
@Override
public final boolean equals(final Object copy) {

    boolean result = copy != null && copy instanceof HardwareAddress && this.getClass().equals(copy.getClass());

    if (result) {

        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())
                    && !Modifier.isTransient(field.getModifiers())) {
                try {

                    if ((field.get(this) != null && field.get(copy) == null)
                            || (field.get(this) == null && field.get(copy) != null)) {
                        result = false;
                    } else if (field.get(this) != null && field.get(copy) != null) {

                        if (field.getType().isArray()) {

                            if (Object[].class.isAssignableFrom(field.getType())) {
                                result = Arrays.equals((Object[]) field.get(this), (Object[]) field.get(copy));
                            } else {
                                result = ArrayUtils.isEquals(field.get(this), field.get(copy));
                            }

                        } else {
                            result = field.get(this).equals(field.get(copy));
                        }
                    }
                } catch (Exception e) {
                    result = false;
                }
            }

            if (!result) {
                break;
            }
        }
    }

    return result;
}

From source file:net.stickycode.mockwire.spring30.MockwireFieldInjectionAnnotationBeanPostProcessor.java

private InjectionMetadata buildAutowiringMetadata(Class clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {/*from  w w w .j a v a 2 s . co m*/
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
        for (Field field : targetClass.getDeclaredFields()) {
            Annotation annotation = findAutowiredAnnotation(field);
            if (annotation != null) {
                if (Modifier.isStatic(field.getModifiers())) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Autowired annotation is not supported on static fields: " + field);
                    }
                    continue;
                }
                boolean required = determineRequiredStatus(annotation);
                currElements.add(new AutowiredFieldElement(field, required));
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while (targetClass != null && targetClass != Object.class);

    return new InjectionMetadata(clazz, elements);
}

From source file:net.abhinavsarkar.spelhelper.SpelHelper.java

private static List<Method> filterMethods(final Class<?> clazz) {
    List<Method> allowedMethods = new ArrayList<Method>();
    for (Method method : clazz.getMethods()) {
        int modifiers = method.getModifiers();
        if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)
                && !method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length > 0) {
            allowedMethods.add(method);// ww w .j a  v a  2 s. c o  m
        }
    }
    return allowedMethods;
}

From source file:common.utils.ReflectionAssert.java

/**
 * All fields are checked for null values (except the static ones).
 * Private fields are also checked./*w  w w .  j a  va 2 s .  c  o m*/
 * This is NOT recursive, only the values of the first object will be checked.
 * An assertion error will be thrown when a property is null.
 * 
 * @param message    a message for when the assertion fails
 * @param object     the object that will be checked for null values.
 */
public static void assertPropertiesNotNull(String message, Object object) {
    Set<Field> fields = ReflectionUtils.getAllFields(object.getClass());
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            String formattedMessage = formatMessage(message,
                    "Property '" + field.getName() + "' in object '" + object.toString() + "' is null ");
            assertNotNull(formattedMessage, ReflectionUtils.getFieldValue(object, field));
        }
    }

}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static Field findField(Class<?> clazz, String propName) {
    Class<?> c = clazz;//from w  w  w  . j  a  va2  s  .c  o m
    while (c != null) {
        for (Field f : c.getDeclaredFields()) {
            if (!f.getName().equals(propName)) {
                continue;
            }
            int modifiers = f.getModifiers();
            if (Modifier.isStatic(modifiers)) {
                continue;
            }
            return f;
        }
        c = c.getSuperclass();
    }
    return null;
}

From source file:org.apache.tinkerpop.gremlin.util.CoreImports.java

/**
 * Filters to unique method names on each class.
 *//*w  ww .  j  a v a2  s .  co  m*/
private static Stream<Method> uniqueMethods(final Class<?> clazz) {
    final Set<String> unique = new HashSet<>();
    return Stream.of(clazz.getMethods()).filter(m -> Modifier.isStatic(m.getModifiers()))
            .map(m -> Pair.with(generateMethodDescriptor(m), m)).filter(p -> {
                final boolean exists = unique.contains(p.getValue0());
                if (!exists)
                    unique.add(p.getValue0());
                return !exists;
            }).map(Pair::getValue1);
}

From source file:com.espertech.esper.epl.core.EngineImportServiceImpl.java

public Method resolveMethod(String className, String methodName) throws EngineImportException {
    Class clazz;//from  w ww . j a va2 s. co m
    try {
        clazz = resolveClassInternal(className, false);
    } catch (ClassNotFoundException e) {
        throw new EngineImportException(
                "Could not load class by name '" + className + "', please check imports", e);
    }

    Method methods[] = clazz.getMethods();
    Method methodByName = null;

    // check each method by name
    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            if (methodByName != null) {
                throw new EngineImportException("Ambiguous method name: method by name '" + methodName
                        + "' is overloaded in class '" + className + "'");
            }
            int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
                methodByName = method;
            }
        }
    }

    if (methodByName == null) {
        throw new EngineImportException(
                "Could not find static method named '" + methodName + "' in class '" + className + "'");
    }
    return methodByName;
}