Example usage for java.lang.reflect Modifier STATIC

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

Introduction

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

Prototype

int STATIC

To view the source code for java.lang.reflect Modifier STATIC.

Click Source Link

Document

The int value representing the static modifier.

Usage

From source file:com.comphenix.protocol.wrappers.WrappedDataWatcher.java

/**
 * Sets the DataWatcher Item associated with a given watcher object to a
 * new value. If there is not already an object at this index, the
 * specified watcher object must have a serializer.
 * //  w w  w. ja v  a2 s.  co  m
 * @param object Associated watcher object
 * @param value New value
 * 
 * @throws IllegalArgumentException If the watcher object is null or must
 *          have a serializer and does not have one.
 */
public void setObject(WrappedDataWatcherObject object, Object value, boolean update) {
    Validate.notNull(object, "Watcher object cannot be null!");

    if (SETTER == null && REGISTER == null) {
        FuzzyReflection fuzzy = FuzzyReflection.fromClass(handleType, true);
        FuzzyMethodContract contract = FuzzyMethodContract.newBuilder().banModifier(Modifier.STATIC)
                .requireModifier(Modifier.PUBLIC).parameterExactArray(object.getHandleType(), Object.class)
                .build();
        List<Method> methods = fuzzy.getMethodList(contract);
        for (Method method : methods) {
            if (method.getName().equals("set") || method.getName().equals("watch")) {
                SETTER = Accessors.getMethodAccessor(method);
            } else {
                REGISTER = Accessors.getMethodAccessor(method);
            }
        }
    }

    // Unwrap the object
    value = WrappedWatchableObject.getUnwrapped(value);

    if (hasIndex(object.getIndex())) {
        SETTER.invoke(handle, object.getHandle(), value);
    } else {
        object.checkSerializer();
        REGISTER.invoke(handle, object.getHandle(), value);
    }

    if (update) {
        getWatchableObject(object.getIndex()).setDirtyState(update);
    }
}

From source file:de.xaniox.heavyspleef.core.flag.FlagRegistry.java

private Method[] getInitMethods(FlagClassHolder holder) {
    Class<? extends AbstractFlag<?>> clazz = holder.flagClass;
    List<Method> methods = Lists.newArrayList();

    for (Method method : clazz.getDeclaredMethods()) {
        if (!method.isAnnotationPresent(FlagInit.class)) {
            continue;
        }/*from w  w w . j  av  a 2s.c o  m*/

        if ((method.getModifiers() & Modifier.STATIC) == 0) {
            continue;
        }

        method.setAccessible(true);
        methods.add(method);
    }

    return methods.toArray(new Method[methods.size()]);
}

From source file:com.mobile.system.db.abatis.AbatisService.java

/**
 * //from   w w w .j a  v  a 2  s  . co m
 * @param jsonStr
 *            JSON String
 * @param beanClass
 *            Bean class
 * @param basePackage
 *            Base package name which includes all Bean classes
 * @return Object Bean
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception {
    Object obj = null;
    JSONObject jsonObj = new JSONObject(jsonStr);
    // Check bean object
    if (beanClass == null) {
        Log.d(TAG, "Bean class is null");
        return null;
    }
    // Read Class member fields
    Field[] props = beanClass.getDeclaredFields();
    if (props == null || props.length == 0) {
        Log.d(TAG, "Class" + beanClass.getName() + " has no fields");
        return null;
    }
    // Create instance of this Bean class
    obj = beanClass.newInstance();
    // Set value of each member variable of this object
    for (int i = 0; i < props.length; i++) {
        String fieldName = props[i].getName();
        // Skip public and static fields
        if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) {
            continue;
        }
        // Date Type of Field
        Class type = props[i].getType();
        String typeName = type.getName();
        // Check for Custom type
        if (typeName.equals("int")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getInt(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("long")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getLong(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.lang.String")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getString(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("double")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getDouble(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.util.Date")) { // modify

            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);

            String dateString = jsonObj.getString(fieldName);
            dateString = dateString.replace(" KST", "");
            SimpleDateFormat genderFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.KOREA);
            // Set value
            try {
                Date afterDate = genderFormat.parse(dateString);
                m.invoke(obj, afterDate);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        } else if (type.getName().equals(List.class.getName())
                || type.getName().equals(ArrayList.class.getName())) {
            // Find out the Generic
            String generic = props[i].getGenericType().toString();
            if (generic.indexOf("<") != -1) {
                String genericType = generic.substring(generic.lastIndexOf("<") + 1, generic.lastIndexOf(">"));
                if (genericType != null) {
                    JSONArray array = null;
                    try {
                        array = jsonObj.getJSONArray(fieldName);
                    } catch (Exception ex) {
                        Log.d(TAG, ex.getMessage());
                        array = null;
                    }
                    if (array == null) {
                        continue;
                    }
                    ArrayList arrayList = new ArrayList();
                    for (int j = 0; j < array.length(); j++) {
                        arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType),
                                basePackage));
                    }
                    // Set value
                    Class[] parms = { type };
                    Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                    m.setAccessible(true);
                    m.invoke(obj, arrayList);
                }
            } else {
                // No generic defined
                generic = null;
            }
        } else if (typeName.startsWith(basePackage)) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                JSONObject customObj = jsonObj.getJSONObject(fieldName);
                if (customObj != null) {
                    m.invoke(obj, parse(customObj.toString(), type, basePackage));
                }
            } catch (JSONException ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else {
            // Skip
            Log.d(TAG, "Field " + fieldName + "#" + typeName + " is skip");
        }
    }
    return obj;
}

From source file:org.codehaus.groovy.grails.compiler.injection.GrailsASTUtils.java

/**
 * Adds a static method to the given class node that delegates to the given method
 * and resolves the object to invoke the method on from the given expression.
 *
 * @param expression The expression/*ww  w.j  a  v a2 s  .  co m*/
 * @param classNode The class node
 * @param delegateMethod The delegate method
 * @param markerAnnotation A marker annotation to be added to all methods
 * @return The added method node or null if it couldn't be added
 */
public static MethodNode addDelegateStaticMethod(Expression expression, ClassNode classNode,
        MethodNode delegateMethod, AnnotationNode markerAnnotation,
        Map<String, ClassNode> genericsPlaceholders) {
    Parameter[] parameterTypes = delegateMethod.getParameters();
    String declaredMethodName = delegateMethod.getName();
    if (classNode.hasDeclaredMethod(declaredMethodName, copyParameters(parameterTypes, genericsPlaceholders))) {
        return null;
    }

    BlockStatement methodBody = new BlockStatement();
    ArgumentListExpression arguments = new ArgumentListExpression();

    for (Parameter parameterType : parameterTypes) {
        arguments.addExpression(new VariableExpression(parameterType.getName()));
    }
    MethodCallExpression methodCallExpression = new MethodCallExpression(expression, declaredMethodName,
            arguments);
    methodCallExpression.setMethodTarget(delegateMethod);

    ThrowStatement missingMethodException = createMissingMethodThrowable(classNode, delegateMethod);
    VariableExpression apiVar = addApiVariableDeclaration(expression, delegateMethod, methodBody);
    IfStatement ifStatement = createIfElseStatementForApiMethodCall(methodCallExpression, apiVar,
            missingMethodException);

    methodBody.addStatement(ifStatement);
    ClassNode returnType = replaceGenericsPlaceholders(delegateMethod.getReturnType(), genericsPlaceholders);
    if (METHOD_MISSING_METHOD_NAME.equals(declaredMethodName)) {
        declaredMethodName = STATIC_METHOD_MISSING_METHOD_NAME;
    }
    MethodNode methodNode = classNode.getDeclaredMethod(declaredMethodName, parameterTypes);
    if (methodNode == null) {
        methodNode = new MethodNode(declaredMethodName, Modifier.PUBLIC | Modifier.STATIC, returnType,
                copyParameters(parameterTypes, genericsPlaceholders),
                GrailsArtefactClassInjector.EMPTY_CLASS_ARRAY, methodBody);
        methodNode.addAnnotations(delegateMethod.getAnnotations());
        if (shouldAddMarkerAnnotation(markerAnnotation, methodNode)) {
            methodNode.addAnnotation(markerAnnotation);
        }

        classNode.addMethod(methodNode);
    }
    return methodNode;
}

From source file:com.offbynull.coroutines.instrumenter.asm.InstructionUtils.java

/**
 * Calls a method with a set of arguments. After execution the stack may have an extra item pushed on it: the object that was returned
 * by this method (if any).//from www.jav  a  2s .  c  o  m
 * @param method method to call
 * @param args method argument instruction lists -- each instruction list must leave one item on the stack of the type expected
 * by the method (note that if this is a non-static method, the first argument must always evaluate to the "this" pointer/reference)
 * @return instructions to invoke a method
 * @throws NullPointerException if any argument is {@code null} or array contains {@code null}
 * @throws IllegalArgumentException if the length of {@code args} doesn't match the number of parameters in {@code method}
 */
public static InsnList call(Method method, InsnList... args) {
    Validate.notNull(method);
    Validate.notNull(args);
    Validate.noNullElements(args);

    InsnList ret = new InsnList();

    for (InsnList arg : args) {
        ret.add(arg);
    }

    Type clsType = Type.getType(method.getDeclaringClass());
    Type methodType = Type.getType(method);

    if ((method.getModifiers() & Modifier.STATIC) == Modifier.STATIC) {
        Validate.isTrue(method.getParameterCount() == args.length);
        ret.add(new MethodInsnNode(Opcodes.INVOKESTATIC, clsType.getInternalName(), method.getName(),
                methodType.getDescriptor(), false));
    } else if (method.getDeclaringClass().isInterface()) {
        Validate.isTrue(method.getParameterCount() + 1 == args.length);
        ret.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, clsType.getInternalName(), method.getName(),
                methodType.getDescriptor(), true));
    } else {
        Validate.isTrue(method.getParameterCount() + 1 == args.length);
        ret.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, clsType.getInternalName(), method.getName(),
                methodType.getDescriptor(), false));
    }

    return ret;
}

From source file:org.gvnix.addon.jpa.addon.audit.JpaAuditMetadata.java

/**
 * @return gets or creates/*from  w  w w  .  jav a2s . c om*/
 *         findRevison(fromRevsion,toRevision,filter,order,start,limit)
 *         method
 */
private MethodMetadata getFindRevisionsMethod() {
    // method name
    JavaSymbolName methodName = findRevisionsMethodName;

    // Define method parameter types
    List<AnnotatedJavaType> parameterTypes = helper.toAnnotedJavaType(JavaType.LONG_OBJECT,
            JavaType.LONG_OBJECT, MAP_STRING_OBJECT, LIST_STRING, JavaType.INT_OBJECT, JavaType.INT_OBJECT);

    // Check if a method exist in type
    final MethodMetadata method = helper.methodExists(methodName, parameterTypes);
    if (method != null) {
        // If it already exists, just return the method
        return method;
    }

    // Define method annotations (none in this case)
    List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();

    // Define method throws types (none in this case)
    List<JavaType> throwsTypes = new ArrayList<JavaType>();

    // Define method parameter names (none in this case)
    List<JavaSymbolName> parameterNames = helper.toSymbolName("fromRevision", "toRevision", "filterMap",
            "order", "start", "limit");

    // Create the method body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    revisionLogBuilder.buildBodyFindRevision(bodyBuilder, parameterNames);

    // Use the MethodMetadataBuilder for easy creation of MethodMetadata
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC + Modifier.STATIC,
            methodName, revisonItemListType, parameterTypes, parameterNames, bodyBuilder);
    methodBuilder.setAnnotations(annotations);
    methodBuilder.setThrowsTypes(throwsTypes);

    return methodBuilder.build(); // Build and return a MethodMetadata
}

From source file:com.adaptc.mws.plugins.testing.transformations.TestMixinTransformation.java

/**
 * Adds a static method to the given class node that delegates to the given method
 * and resolves the object to invoke the method on from the given expression.
 *
 * @param expression The expression/* www  . j a v  a2 s  . com*/
 * @param classNode The class node
 * @param delegateMethod The delegate method
 * @return The added method node or null if it couldn't be added
 */
public static MethodNode addDelegateStaticMethod(Expression expression, ClassNode classNode,
        MethodNode delegateMethod) {
    Parameter[] parameterTypes = delegateMethod.getParameters();
    String declaredMethodName = delegateMethod.getName();
    if (classNode.hasDeclaredMethod(declaredMethodName, parameterTypes)) {
        return null;
    }

    BlockStatement methodBody = new BlockStatement();
    ArgumentListExpression arguments = new ArgumentListExpression();

    for (Parameter parameterType : parameterTypes) {
        arguments.addExpression(new VariableExpression(parameterType.getName()));
    }
    MethodCallExpression methodCallExpression = new MethodCallExpression(expression, declaredMethodName,
            arguments);
    methodCallExpression.setMethodTarget(delegateMethod);

    ThrowStatement missingMethodException = createMissingMethodThrowable(classNode, delegateMethod);
    VariableExpression apiVar = addApiVariableDeclaration(expression, delegateMethod, methodBody);
    IfStatement ifStatement = createIfElseStatementForApiMethodCall(methodCallExpression, apiVar,
            missingMethodException);

    methodBody.addStatement(ifStatement);
    ClassNode returnType = nonGeneric(delegateMethod.getReturnType());
    if (METHOD_MISSING_METHOD_NAME.equals(declaredMethodName)) {
        declaredMethodName = STATIC_METHOD_MISSING_METHOD_NAME;
    }
    MethodNode methodNode = classNode.getDeclaredMethod(declaredMethodName, parameterTypes);
    if (methodNode == null) {
        methodNode = new MethodNode(declaredMethodName, Modifier.PUBLIC | Modifier.STATIC, returnType,
                copyParameters(parameterTypes), EMPTY_CLASS_ARRAY, methodBody);
        methodNode.addAnnotations(delegateMethod.getAnnotations());

        classNode.addMethod(methodNode);
    }
    return methodNode;
}

From source file:org.gvnix.addon.jpa.addon.audit.JpaAuditMetadata.java

/**
 * @return gets or creates//  w w w . j  ava2 s.  c om
 *         findXXXRevisonByDates(fromDate,toDate,filter,order,start,limit)
 *         method
 */
private MethodMetadata getFindRevisionByDatesMethod() {
    // method name
    JavaSymbolName methodName = findRevisionsByDatesMethodName;

    // Define method parameter types
    List<AnnotatedJavaType> parameterTypes = helper.toAnnotedJavaType(JdkJavaType.DATE, JdkJavaType.DATE,
            MAP_STRING_OBJECT, LIST_STRING, JavaType.INT_OBJECT, JavaType.INT_OBJECT);

    // Check if a method exist in type
    final MethodMetadata method = helper.methodExists(methodName, parameterTypes);
    if (method != null) {
        // If it already exists, just return the method
        return method;
    }

    // Define method annotations (none in this case)
    List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();

    // Define method throws types (none in this case)
    List<JavaType> throwsTypes = new ArrayList<JavaType>();

    // Define method parameter names (none in this case)
    List<JavaSymbolName> parameterNames = helper.toSymbolName("fromDate", "toDate", "filterMap", "order",
            "start", "limit");

    // Create the method body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    revisionLogBuilder.buildBodyFindRevisionByDates(bodyBuilder, parameterNames);

    // Use the MethodMetadataBuilder for easy creation of MethodMetadata
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC + Modifier.STATIC,
            methodName, revisonItemListType, parameterTypes, parameterNames, bodyBuilder);
    methodBuilder.setAnnotations(annotations);
    methodBuilder.setThrowsTypes(throwsTypes);

    return methodBuilder.build(); // Build and return a MethodMetadata
}

From source file:com.taobao.weex.wson.Wson.java

private static final List<Method> getBeanMethod(String key, Class targetClass) {
    List<Method> methods = methodsCache.get(key);
    if (methods == null) {
        methods = new ArrayList<>();
        Method[] allMethods = targetClass.getMethods();
        for (Method method : allMethods) {
            if (method.getDeclaringClass() == Object.class) {
                continue;
            }//  w  w w  . ja  v  a2s .  c o m
            if ((method.getModifiers() & Modifier.STATIC) != 0) {
                continue;
            }
            String methodName = method.getName();
            if (methodName.startsWith(METHOD_PREFIX_GET) || methodName.startsWith(METHOD_PREFIX_IS)) {
                if (method.getAnnotation(JSONField.class) != null) {
                    throw new UnsupportedOperationException(
                            "getBeanMethod JSONField Annotation Not Handled, Use toJSON");
                }
                methods.add(method);
            }
        }
        methodsCache.put(key, methods);
    }
    return methods;
}

From source file:org.gvnix.web.screen.roo.addon.AbstractPatternMetadata.java

protected FieldMetadataBuilder getGvNIXPatternField() {
    return new FieldMetadataBuilder(getId(), Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL,
            new JavaSymbolName("PATTERN_PARAM_NAME"), JavaType.STRING, "\"" + GVNIXPATTERN + "\"");
}