Java Reflection Field Find findFieldToInject(Class target, String name, Class source)

Here you can find the source of findFieldToInject(Class target, String name, Class source)

Description

find Field To Inject

License

Open Source License

Declaration

public static Field findFieldToInject(Class<?> target, String name, Class<?> source) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Field;

public class Main {
    public static Field findFieldToInject(Class<?> target, String name, Class<?> source) {

        Field f = getField(target, name);

        if (f != null) {

            Class<?> type = f.getType();

            if (type.isAssignableFrom(source) || checkPrimitives(type, source)) {

                f.setAccessible(true);/* w ww.  ja  v a2s  .c o m*/

                return f;
            }

        }

        return null;
    }

    public static Field getField(Object target, String name) {
        return getField(target.getClass(), name);
    }

    public static Field getField(Class<?> target, String name) {
        Field[] fields = target.getDeclaredFields();
        for (Field field : fields) {
            if (name.equals(field.getName())) {
                return field;
            }
        }
        return null;
    }

    public static boolean checkPrimitives(Class<?> target, Class<?> source) {

        if (target.equals(int.class) && source.equals(Integer.class)) {
            return true;
        }

        if (target.equals(boolean.class) && source.equals(Boolean.class)) {
            return true;
        }

        if (target.equals(byte.class) && source.equals(Byte.class)) {
            return true;
        }

        if (target.equals(short.class) && source.equals(Short.class)) {
            return true;
        }

        if (target.equals(char.class) && source.equals(Character.class)) {
            return true;
        }

        if (target.equals(long.class) && source.equals(Long.class)) {
            return true;
        }

        if (target.equals(float.class) && source.equals(Float.class)) {
            return true;
        }

        return target.equals(double.class) && source.equals(Double.class);

    }
}

Related

  1. findFields(Class type)
  2. findFields(final Class clazz, final Predicate filter)
  3. findFieldsAnnotatedWith(Class annotation, Class parentClass)
  4. findFieldsAnnotatedWith(final Class type, final Class annotation)
  5. findFieldsOfClass(Class target, Object o, String path, Logger log, Set done)
  6. findFieldType(Field field, Class concreteClass)
  7. findFieldWithAnnotation(String fieldName, Class clazz, Class annotationType)