Example usage for java.lang.reflect Field isAnnotationPresent

List of usage examples for java.lang.reflect Field isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang.reflect Field isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:me.anon.lib.Views.java

private static void inject(final Object target, Object source, Finder finder) {
    if (target.getClass().getDeclaredFields() != null) {
        ArrayList<Method> methods = new ArrayList<Method>();
        ArrayList<Field> fields = new ArrayList<Field>();
        Class objOrSuper = target.getClass();

        if (!objOrSuper.isAnnotationPresent(Injectable.class)) {
            Log.e("InjectView", "No Injectable annotation for class " + objOrSuper);
            return;
        }/*  w w w . java2  s .com*/

        while (objOrSuper.isAnnotationPresent(Injectable.class)) {
            for (Field field : objOrSuper.getDeclaredFields()) {
                if (field.isAnnotationPresent(InjectView.class) || field.isAnnotationPresent(InjectViews.class)
                        || field.isAnnotationPresent(InjectFragment.class)
                        || field.isAnnotationPresent(OnClick.class)) {
                    fields.add(field);
                }
            }

            for (Method method : objOrSuper.getDeclaredMethods()) {
                if (method.isAnnotationPresent(OnClick.class)) {
                    methods.add(method);
                }
            }

            objOrSuper = objOrSuper.getSuperclass();
        }

        for (Field field : fields) {
            if (field.isAnnotationPresent(InjectView.class)) {
                InjectView a = (InjectView) field.getAnnotation(InjectView.class);

                try {
                    field.setAccessible(true);

                    int id = ((InjectView) a).value();
                    if (id < 1) {
                        String key = ((InjectView) a).id();
                        if (TextUtils.isEmpty(key)) {
                            key = field.getName();
                            key = key.replaceAll("(.)([A-Z])", "$1_$2").toLowerCase(Locale.ENGLISH);
                        }

                        Field idField = R.id.class.getField(key);
                        id = idField.getInt(null);
                    }

                    View v = finder.findById(source, id);

                    if (v != null) {
                        field.set(target, v);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (field.isAnnotationPresent(InjectViews.class)) {
                try {
                    InjectViews annotation = (InjectViews) field.getAnnotation(InjectViews.class);
                    field.setAccessible(true);

                    int[] ids = annotation.value();
                    String[] strIds = annotation.id();
                    Class[] instances = annotation.instances();

                    List<View> views = new ArrayList<View>(ids.length);

                    if (ids.length > 0) {
                        for (int index = 0; index < ids.length; index++) {
                            View v = finder.findById(source, ids[index]);
                            views.add(index, v);
                        }
                    } else if (strIds.length > 0) {
                        for (int index = 0; index < ids.length; index++) {
                            String key = annotation.id()[index];
                            Field idField = R.id.class.getField(key);
                            int id = idField.getInt(null);

                            View v = finder.findById(source, id);
                            views.add(index, v);
                        }
                    } else if (instances.length > 0) {
                        for (int index = 0; index < instances.length; index++) {
                            List<View> v = finder.findByInstance(source, instances[index]);
                            views.addAll(v);
                        }
                    }

                    field.set(target, views);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (field.isAnnotationPresent(InjectFragment.class)) {
                InjectFragment annotation = (InjectFragment) field.getAnnotation(InjectFragment.class);

                try {
                    field.setAccessible(true);

                    int id = ((InjectFragment) annotation).value();
                    Object fragment = null;

                    if (id < 1) {
                        String tag = ((InjectFragment) annotation).tag();

                        fragment = finder.findFragmentByTag(source, tag);
                    } else {
                        fragment = finder.findFragmentById(source, id);
                    }

                    if (fragment != null) {
                        field.set(target, fragment);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (field.isAnnotationPresent(OnClick.class)) {
                OnClick annotation = (OnClick) field.getAnnotation(OnClick.class);

                try {
                    if (field.get(target) != null) {
                        final View view = ((View) field.get(target));

                        if (!TextUtils.isEmpty(annotation.method())) {
                            final String clickName = annotation.method();
                            view.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    try {
                                        Class<?> c = Class.forName(target.getClass().getCanonicalName());
                                        Method m = c.getMethod(clickName, View.class);
                                        m.invoke(target, v);
                                    } catch (Exception e) {
                                        throw new IllegalArgumentException("Method not found " + clickName);
                                    }
                                }
                            });
                        } else {
                            view.setOnClickListener((View.OnClickListener) target);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        for (final Method method : methods) {
            if (method.isAnnotationPresent(OnClick.class)) {
                final OnClick annotation = (OnClick) method.getAnnotation(OnClick.class);
                final String clickName = method.getName();

                try {
                    int id = annotation.value();
                    if (id < 1) {
                        String key = annotation.id();

                        if (TextUtils.isEmpty(key)) {
                            key = clickName;
                            key = key.replaceAll("^(on)?(.*)Click$", "$2");
                            key = key.replaceAll("(.)([A-Z])", "$1_$2").toLowerCase(Locale.ENGLISH);
                        }

                        Field field = R.id.class.getField(key);
                        id = field.getInt(null);
                    }

                    View view = finder.findById(source, id);
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                if (method != null && method.getParameterTypes().length > 0) {
                                    Class<?> paramType = method.getParameterTypes()[0];
                                    method.setAccessible(true);
                                    method.invoke(target, paramType.cast(v));
                                } else if (method != null && method.getParameterTypes().length < 1) {
                                    method.setAccessible(true);
                                    method.invoke(target);
                                } else {
                                    new IllegalArgumentException(
                                            "Failed to find method " + clickName + " with nil or View params")
                                                    .printStackTrace();
                                }
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private static void buildTree(IOEntity entity, Field listField, TreeView<Object> elements, String nameFilter) {
    elements.setRoot(null);/*from   w  w  w  . j a va2  s  .c o  m*/

    if (entity == null)
        return;

    try {
        List<IOEntity> list = (List<IOEntity>) listField.get(entity);
        if (!listField.isAnnotationPresent(Type.class)) {
            log.log(Level.WARNING, String.format("XDAT.%s: @Type not defined", listField.getName()));
            Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                    String.format("XDAT.%s: @Type not defined", listField.getName()));
        } else {
            Class<? extends IOEntity> type = listField.getAnnotation(Type.class).value()
                    .asSubclass(IOEntity.class);
            TreeItem<Object> rootItem = new TreeItem<>(new ListHolder(entity, list, listField.getName(), type));

            elements.setRoot(rootItem);

            rootItem.getChildren().addAll(list.stream().map(Controller::createTreeItem)
                    .filter(treeItem -> checkTreeNode(treeItem, nameFilter)).collect(Collectors.toList()));
        }
    } catch (IllegalAccessException e) {
        log.log(Level.WARNING, String.format("%s.%s is not accessible",
                listField.getDeclaringClass().getSimpleName(), listField.getName()), e);
        Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                listField.getDeclaringClass().getSimpleName() + "." + listField.getName()
                        + " is not accessible");
    }
}

From source file:nl.knaw.dans.dccd.application.services.DccdProjectValidationService.java

/**
 * Determine if annotation is present and the field is required
 *
 * Note: This function is called often and optimizing it was needed
 * /*from   ww w . j a va  2s . c o  m*/
 * @param classField
 * @return
 */
static private boolean isFieldRequired(final java.lang.reflect.Field classField) {
    if (classField.isAnnotationPresent(XmlElement.class)) {
        //logger.debug("Inspecting annotations for " + XmlElement.class.getSimpleName());
        return (classField.getAnnotation(XmlElement.class).required());
    } else if (classField.isAnnotationPresent(XmlAttribute.class)) {
        // assume it can not have both Element and Attribute annotations 
        //logger.debug("Inspecting annotations for " + XmlAttribute.class.getSimpleName());
        return (classField.getAnnotation(XmlAttribute.class).required());
    } else {
        return false;
    }
}

From source file:com.github.dactiv.common.utils.ReflectionUtils.java

/**
 * ?fieldannotationClass//from   w  ww  .jav  a2s .co  m
 * 
 * @param field
 *            field
 * @param annotationClass
 *            annotationClass
 * 
 * @return {@link Annotation}
 */
public static <T extends Annotation> T getAnnotation(Field field, Class annotationClass) {

    Assert.notNull(field, "field?");
    Assert.notNull(annotationClass, "annotationClass?");

    field.setAccessible(true);
    if (field.isAnnotationPresent(annotationClass)) {
        return (T) field.getAnnotation(annotationClass);
    }
    return null;
}

From source file:adalid.core.XS1.java

private static CastingField getCastingFieldAnnotation(Field declaringField, Class<?> fieldType) {
    if (Property.class.isAssignableFrom(fieldType) || Parameter.class.isAssignableFrom(fieldType)) {
        if (declaringField.isAnnotationPresent(CastingField.class)) {
            return declaringField.getAnnotation(CastingField.class);
        }/*  w w w.jav  a 2  s .  c  om*/
    }
    return null;
}

From source file:com.ryantenney.metrics.spring.AnnotationFilter.java

@Override
public boolean matches(Field field) {
    return field.isAnnotationPresent(clazz);
}

From source file:org.jongo.marshall.jackson.JacksonIdFieldSelector.java

public boolean isObjectId(Field f) {
    return f.isAnnotationPresent(org.jongo.marshall.jackson.oid.ObjectId.class)
            || f.isAnnotationPresent(MongoObjectId.class) || ObjectId.class.isAssignableFrom(f.getType());
}

From source file:com.sqewd.open.dal.reflect.test.AnnotationTest.java

public void run() {
    try {/*from  ww w .  ja v a 2 s.  co  m*/
        EntityClassLoader loader = new EntityClassLoader();
        loader.loadClass("com.sqewd.open.dal.reflect.test.TestEntity");

        Class.forName("com.sqewd.open.dal.reflect.test.TestEntity");
        TestEntity entity = new TestEntity();

        JsonRootName re = entity.getClass().getAnnotation(JsonRootName.class);
        if (re != null) {
            System.out.println("ROOT : " + re.value());
        }
        Field[] fields = entity.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field fd : fields) {
                if (fd.isAnnotationPresent(JsonProperty.class)) {
                    JsonProperty attr = fd.getAnnotation(JsonProperty.class);
                    System.out.println("Field : " + fd.getName() + " --> " + attr.value());
                }
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java

/**
 * Returns true if the given annotation is hidden from the help system.
 * @param field Field to test.//from   w  w w .j a  va 2  s.c o m
 * @return True if argument should be hidden.  False otherwise.
 */
public static boolean isArgumentHidden(Field field) {
    return field.isAnnotationPresent(Hidden.class);
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ??//from www. ja  va  2  s.co m
 * @param context 
 * @param request 
 * @param requestParams ??null????????
 * @return ?
 */
@SuppressWarnings("unchecked")
public static RequestParams parseRequestParams(Context context, Request request, RequestParams requestParams) {
    if (requestParams == null) {
        requestParams = new RequestParams();
    }

    String requestParamName;
    String requestParamValue;
    Object requestParamValueObject = null;
    for (Field field : getFields(request.getClass(), true, true, true)) {
        // ????
        if (!field.isAnnotationPresent(Param.class)) {
            continue;
        }

        // ????
        requestParamName = parseParamAnnotation(context, field);
        if (requestParamName == null) {
            requestParamName = field.getName();
        }

        // ?ValueValue?
        if (field.isAnnotationPresent(Value.class)) {
            String value = parseValueAnnotation(context, field);
            if (value != null) {
                requestParams.put(requestParamName, value);
                continue;
            }
        }

        try {
            field.setAccessible(true);
            requestParamValueObject = field.get(request);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // ?null?
        if (requestParamValueObject == null) {
            continue;
        }

        // ?Map???
        if (Map.class.isAssignableFrom(field.getType())) {
            for (java.util.Map.Entry<Object, Object> entry : ((Map<Object, Object>) requestParamValueObject)
                    .entrySet()) {
                if (entry.getKey() != null && entry.getValue() != null) {
                    String key = entry.getKey().toString();
                    String value = entry.getValue().toString();
                    if (key != null && !"".equals(key) && value != null && !"".equals(value)) {
                        requestParams.put(key, value);
                    }
                }
            }
            continue;
        }

        // ?File?
        if (File.class.isAssignableFrom(field.getType())) {
            try {
                requestParams.put(requestParamName, (File) requestParamValueObject);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            continue;
        }

        // ?ArrayListArrayList?
        if (ArrayList.class.isAssignableFrom(field.getType())) {
            requestParams.put(requestParamName, (ArrayList<String>) requestParamValueObject);
            continue;
        }

        // ?boolean
        if (Boolean.class.isAssignableFrom(field.getType())) {
            if ((Boolean) requestParamValueObject) {
                requestParamValue = parseTrueAnnotation(context, field);
                if (requestParamValue == null) {
                    requestParamValue = DEFAULT_VALUE_TRUE;
                }
            } else {
                requestParamValue = parseFalseAnnotation(context, field);
                if (requestParamValue == null) {
                    requestParamValue = DEFAULT_VALUE_FALSE;
                }
            }
            requestParams.put(requestParamName, requestParamValue);
            continue;
        }

        // ?
        if (Enum.class.isAssignableFrom(field.getType())) {
            Enum<?> enumObject = (Enum<?>) requestParamValueObject;
            requestParamValue = parseValueAnnotationFromEnum(context, enumObject);
            if (requestParamValue == null) {
                requestParamValue = enumObject.name();
            }
            requestParams.put(requestParamName, requestParamValue);
            continue;
        }

        // ???
        requestParamValue = requestParamValueObject.toString();
        if (requestParamValue != null && !"".equals(requestParamValue)) {
            requestParams.put(requestParamName, requestParamValue);
        }
    }

    return requestParams;
}