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:adalid.core.Operation.java

void initialiseFields(Class<?> clazz) {
    Class<?> c;//from w  w  w.j a v  a 2  s.com
    int d, r;
    String name;
    Class<?> type;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = depth();
    int round = round();
    Class<?>[] classes = new Class<?>[] { Parameter.class, Expression.class };
    Class<?> dac = getClass();
    Class<?> top = Operation.class;
    int i = ArrayUtils.indexOf(classes, clazz);
    if (i != ArrayUtils.INDEX_NOT_FOUND) {
        c = classes[i];
        for (Field field : XS1.getFields(dac, top)) {
            field.setAccessible(true);
            logger.trace(field);
            name = field.getName();
            type = field.getType();
            if (!c.isAssignableFrom(type)) {
                continue;
            }
            modifiers = type.getModifiers();
            if (type.isInterface() && Expression.class.isAssignableFrom(type)) {
                restricted = false;
            } else {
                restricted = Modifier.isAbstract(modifiers);
            }
            restricted = restricted || !Modifier.isPublic(modifiers);
            if (restricted) {
                continue;
            }
            modifiers = field.getModifiers();
            restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
            if (restricted) {
                continue;
            }
            String errmsg = "failed to create a new instance of field \"" + field + "\" at " + this;
            try {
                o = field.get(this);
                if (o == null) {
                    logger.debug(message(type, name, o, depth, round));
                    o = XS1.initialiseField(this, field);
                    if (o == null) {
                        logger.debug(message(type, name, o, depth, round));
                        //                          throw new RuntimeException(message(type, name, o, depth, round));
                    } else {
                        logger.debug(message(type, name, o, depth, round));
                        field.set(this, o);
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new InstantiationRuntimeException(errmsg, ex);
            }
        }
    }
}

From source file:ca.uhn.fhir.rest.server.RestfulServer.java

private int findResourceMethods(Object theProvider, Class<?> clazz) throws ConfigurationException {
    int count = 0;

    for (Method m : ReflectionUtil.getDeclaredMethods(clazz)) {
        BaseMethodBinding<?> foundMethodBinding = BaseMethodBinding.bindMethod(m, getFhirContext(),
                theProvider);// w  w w  . ja v a  2  s . c om
        if (foundMethodBinding == null) {
            continue;
        }

        count++;

        if (foundMethodBinding instanceof ConformanceMethodBinding) {
            myServerConformanceMethod = foundMethodBinding;
            continue;
        }

        if (!Modifier.isPublic(m.getModifiers())) {
            throw new ConfigurationException(
                    "Method '" + m.getName() + "' is not public, FHIR RESTful methods must be public");
        } else {
            if (Modifier.isStatic(m.getModifiers())) {
                throw new ConfigurationException(
                        "Method '" + m.getName() + "' is static, FHIR RESTful methods must not be static");
            } else {
                ourLog.debug("Scanning public method: {}#{}", theProvider.getClass(), m.getName());

                String resourceName = foundMethodBinding.getResourceName();
                ResourceBinding resourceBinding;
                if (resourceName == null) {
                    resourceBinding = myServerBinding;
                } else {
                    RuntimeResourceDefinition definition = getFhirContext().getResourceDefinition(resourceName);
                    if (myResourceNameToBinding.containsKey(definition.getName())) {
                        resourceBinding = myResourceNameToBinding.get(definition.getName());
                    } else {
                        resourceBinding = new ResourceBinding();
                        resourceBinding.setResourceName(resourceName);
                        myResourceNameToBinding.put(resourceName, resourceBinding);
                    }
                }

                List<Class<?>> allowableParams = foundMethodBinding.getAllowableParamAnnotations();
                if (allowableParams != null) {
                    for (Annotation[] nextParamAnnotations : m.getParameterAnnotations()) {
                        for (Annotation annotation : nextParamAnnotations) {
                            Package pack = annotation.annotationType().getPackage();
                            if (pack.equals(IdParam.class.getPackage())) {
                                if (!allowableParams.contains(annotation.annotationType())) {
                                    throw new ConfigurationException("Method[" + m.toString()
                                            + "] is not allowed to have a parameter annotated with "
                                            + annotation);
                                }
                            }
                        }
                    }
                }

                resourceBinding.addMethod(foundMethodBinding);
                ourLog.debug(" * Method: {}#{} is a handler", theProvider.getClass(), m.getName());
            }
        }
    }

    return count;
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Serializes the given class to the getCurrentDirectory() directory. The
 * static serializedInstance() method of clazz will be called to get an
 * examplar of clazz. This examplar will then be serialized out to a file
 * stored in getCurrentDirectory().//from w  ww . j av a  2s.  c  om
 *
 * @param clazz the class to serialize.
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()
 */
private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    try {
        Field field = clazz.getDeclaredField("serialVersionUID");

        int modifiers = field.getModifiers();
        boolean _static = Modifier.isStatic(modifiers);
        boolean _final = Modifier.isFinal(modifiers);
        field.setAccessible(true);

        if (!_static || !_final || !(23L == field.getLong(null))) {
            throw new RuntimeException(
                    "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0) {
            Method method = clazz.getMethod("serializableInstance");
            Object object = method.invoke(null);

            File file = new File(current, clazz.getName() + ".ser");
            boolean created = file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(object);
            out.close();
        }

        // Make entry in list of class fields.
        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
        String className = objectStreamClass.getName();
        ObjectStreamField[] fields = objectStreamClass.getFields();
        @SuppressWarnings("Convert2Diamond")
        List<String> fieldList = new ArrayList<>();

        for (ObjectStreamField objectStreamField : fields) {
            String fieldName = objectStreamField.getName();
            fieldList.add(fieldName);
        }

        classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz
                + ". Please make one and set it " + "to 23L."));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(
                "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e);
    } catch (IOException e) {
        throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory()
                + " when trying to serialize " + clazz + ".", e);
    }
}

From source file:com.cons.gps2exif.exif.ReadMetaData.java

private static List<Field> getTagInfoDefinedInClass(Class<?> clazz) {
    Field[] declaredFields = clazz.getDeclaredFields();
    return Arrays.stream(declaredFields).filter(
            field -> TagInfo.class.isAssignableFrom(field.getType()) && Modifier.isStatic(field.getModifiers()))
            .collect(Collectors.toList());
}

From source file:net.pms.external.ExternalFactory.java

private static void postInstall(Class<?> clazz) {
    Method postInstall;/*from   w  ww  . j av a2  s. c o m*/
    try {
        postInstall = clazz.getDeclaredMethod("postInstall", (Class<?>[]) null);

        if (Modifier.isStatic(postInstall.getModifiers())) {
            postInstall.invoke((Object[]) null, (Object[]) null);
        }
    }

    // Ignore all errors
    catch (SecurityException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException
            | InvocationTargetException e) {
    }
}

From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java

/**
 * Serializes the given class to the getCurrentDirectory() directory. The
 * static serializedInstance() method of clazz will be called to get an
 * examplar of clazz. This examplar will then be serialized out to a file
 * stored in getCurrentDirectory().//  ww w . java2  s .c om
 *
 * @param clazz the class to serialize.
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()
 */
private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    try {
        Field field = clazz.getDeclaredField("serialVersionUID");

        int modifiers = field.getModifiers();
        boolean _static = Modifier.isStatic(modifiers);
        boolean _final = Modifier.isFinal(modifiers);
        field.setAccessible(true);

        if (!_static || !_final || !(23L == field.getLong(null))) {
            throw new RuntimeException(
                    "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0) {
            Method method = clazz.getMethod("serializableInstance", new Class[0]);
            Object object = method.invoke(null, new Object[0]);

            File file = new File(current, clazz.getName() + ".ser");
            file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(object);
            out.close();
        }

        // Make entry in list of class fields.
        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
        String className = objectStreamClass.getName();
        ObjectStreamField[] fields = objectStreamClass.getFields();
        List<String> fieldList = new ArrayList<String>();

        for (ObjectStreamField objectStreamField : fields) {
            String fieldName = objectStreamField.getName();
            fieldList.add(fieldName);
        }

        classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz
                + ". Please make one and set it " + "to 23L."));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(
                "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e);
    } catch (IOException e) {
        throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory()
                + " when trying to serialize " + clazz + ".", e);
    }
}

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

/**
 * Filters to unique method names on each class.
 *//*  w  w  w .  j av  a  2s  .com*/
private static Stream<Method> uniqueMethods(final Class<?> clazz) {
    final Set<String> unique = new LinkedHashSet<>();
    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:adalid.core.EntityAtlas.java

@SuppressWarnings("deprecation")
void initialiseFields(Class<?> clazz) {
    track("initialiseFields", _declaringArtifact, clazz.getSimpleName());
    Class<?> c;//from  ww  w.j  a va2s.  c  o m
    int d, r;
    String name;
    String key;
    String pattern = "there are several fields for operation {0}";
    String message;
    Class<?> type;
    Class<?> decl;
    Class<?> operationClass;
    Field operationField;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = _declaringArtifact.depth();
    int round = _declaringArtifact.round();
    Class<?>[] classes = new Class<?>[] { Property.class, Key.class, Tab.class, View.class, Instance.class,
            NamedValue.class, Expression.class, Transition.class, Operation.class, Trigger.class };
    Class<?> dac = _declaringArtifact.getClass();
    Class<?> top = Entity.class;
    int i = ArrayUtils.indexOf(classes, clazz);
    if (i != ArrayUtils.INDEX_NOT_FOUND) {
        c = classes[i];
        for (Field field : XS1.getFields(dac, top)) {
            field.setAccessible(true);
            logger.trace(field);
            name = field.getName();
            type = field.getType();
            decl = field.getDeclaringClass();
            if (!c.isAssignableFrom(type)) {
                continue;
            }
            if (c.equals(Expression.class) && Property.class.isAssignableFrom(type)) {
                continue;
            }
            // TODO: extension handling
            if (field.isAnnotationPresent(Extension.class) && Entity.class.isAssignableFrom(type)) {
                //                  if (!dac.equals(decl) || !dac.isAssignableFrom(type)) {
                //                      continue;
                //                  }
                continue;
            }
            modifiers = type.getModifiers();
            if (NamedValue.class.isAssignableFrom(type) || Expression.class.isAssignableFrom(type)) {
                restricted = false;
            } else {
                restricted = type.isInterface() || Modifier.isAbstract(modifiers);
            }
            restricted = restricted || !Modifier.isPublic(modifiers);
            if (restricted) {
                continue;
            }
            modifiers = field.getModifiers();
            restricted = Modifier.isPrivate(modifiers);
            if (restricted) {
                continue;
            }
            restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
            if (restricted) {
                continue;
            }
            if (Operation.class.isAssignableFrom(type)) {
                key = type.getSimpleName();
                operationClass = _operationClasses.get(key);
                if (operationClass != null) {
                    operationField = _operationFields.get(key);
                    if (operationField == null) {
                        _operationFields.put(key, field);
                    } else {
                        message = MessageFormat.format(pattern, operationClass.getName());
                        logger.warn(message);
                        TLC.getProject().getParser().increaseWarningCount();
                    }
                }
            }
            String errmsg = "failed to create a new instance of field \"" + field + "\" at "
                    + _declaringArtifact;
            try {
                o = field.get(_declaringArtifact);
                if (o == null) {
                    logger.debug(message(type, name, o, depth, round));
                    o = XS1.initialiseField(_declaringArtifact, field);
                    if (o == null) {
                        logger.debug(message(type, name, o, depth, round));
                        //                          throw new RuntimeException(message(type, name, o, depth, round));
                    } else {
                        logger.debug(message(type, name, o, depth, round));
                        field.set(_declaringArtifact, o);
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new InstantiationRuntimeException(errmsg, ex);
            }
        }
    }
}

From source file:com.link_intersystems.lang.ContextAware.java

/**
 * Same semantic as {@link #invokeInContext(Object, String, Object...)}, but
 * searches for a static applicable method to invoke.
 * //  w ww  .j  a  va 2  s .co  m
 * @param target
 *            the {@link Class} that holds the static method.
 * @param method
 *            the method name of the static method that should be invoked.
 * @param params
 *            the invokation parameters.
 * @return the invoked method's return value
 * @throws Exception
 *             if the invoked method throws an exception.
 * @since 1.2.0.0
 */
@SuppressWarnings("unchecked")
public <EXPECTED_TYPE> EXPECTED_TYPE invokeStaticInContext(Class<?> target, String method, Object... params)
        throws Exception {
    Class2<?> targetClass2 = Class2.get(target);
    Method2 applicableMethod = targetClass2.getApplicableMethod(method, params);
    if (applicableMethod == null || !Modifier.isStatic(applicableMethod.getModifiers())) {
        throw new IllegalArgumentException(
                "target class doesn't declare a static applicable method called " + method);
    }
    Invokable invokable = applicableMethod.getInvokable(target);
    Callable<EXPECTED_TYPE> callable = invokable.asCallable(params);

    Object methodInvokationResult = runInContext(callable);
    EXPECTED_TYPE expectedType = (EXPECTED_TYPE) methodInvokationResult;
    return expectedType;
}

From source file:com.pwn9.pwnchat.config.ConfigObject.java

protected boolean doSkip(Field field) {
    return Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())
            || Modifier.isFinal(field.getModifiers()) || Modifier.isPrivate(field.getModifiers());
}