Java反射機制(reflection)使用方法歸納

Java反射機制使用方法歸納

封裝方法歸納

通過反射創建對象

/**
 * Create new object instance with type clazz.
 *
 * @param clazz         given type
 * @param constructArgs arguments to construct the object instance
 * @return object instance (null when exception occurred)
 */
public static Object newObjectInstance(Class<?> clazz, Object... constructArgs) {
    Object object;
    try {
        object = null;
        int argCount = constructArgs.length;
        for (Constructor<?> constructor : getConstructorsAll(clazz)) {
            if (constructor.getParameterCount() == argCount) {
                makeConstructorAccessible(constructor);
                object = constructor.newInstance(constructArgs);
            }
        }
    } catch (Exception e) {
        object = null;
    }
    return object;
}

說明:
- 通過傳入的構造器參數個數,調用相應個數的構造方法創建對象

通過名稱獲取類的Class

/**
 * get class type by name (entire name)
 * <p>
 * <pre>
 *     For basic types :
 *      int ---> {@link java.lang.Integer}
 *      float ---> {@link java.lang.Float}
 *      byte ---> {@link java.lang.Byte}
 *      double ---> {@link java.lang.Double}
 *      boolean ---> {@link java.lang.Boolean}
 *      char ---> {@link java.lang.Character}
 *      long ---> {@link java.lang.Long}
 *      short ---> {@link java.lang.Short}
 * </pre>
 *
 * @param name entire name of a type
 * @return class type
 */
public static Class<?> getClassByName(String name) {
    Class<?> clazz;
    switch (name) {
    case "int":
        return Integer.class;
    case "float":
        return Float.class;
    case "byte":
        return Byte.class;
    case "double":
        return Double.class;
    case "boolean":
        return Boolean.class;
    case "char":
        return Character.class;
    case "long":
        return Long.class;
    case "short":
        return Short.class;
    }
    try {
        clazz = Class.forName(name);
    } catch (Exception e) {
        clazz = null;
    }
    return clazz;
}

說明:
- 如果傳入的名稱是基本類型,返回基本類型的Java封裝類型Class

設置對象指定名稱字段值

/**
 * set field value for the given object with given field name
 *
 * @param o     given object
 * @param name  given field name
 * @param value field value to be set
 * @return true/false succeeded or failed
 */
public static boolean setFieldValue(Object o, String name, Object value) {
    boolean result;
    try {
        Field field = o.getClass().getDeclaredField(name);
        makeFieldAccessible(field);
        field.set(o, value);
        result = true;
    } catch (Exception e) {
        result = false;
    }
    return result;
}

說明:
- 設置指定名稱的字段值,如果不存在返回false

獲取對象指定名稱的字段值

/**
 * get field value of given object with given field name
 *
 * @param o    given object
 * @param name given field name
 * @return field value (null if field not exists)
 */
public static Object getFieldValue(Object o, String name) {
    Object value;
    try {
        Field field = o.getClass().getDeclaredField(name);
        makeFieldAccessible(field);
        value = field.get(o);
    } catch (Exception e) {
        value = null;
    }
    return value;
}

說明:
- 獲取指定名稱的字段值,若沒有這個字段返回null

獲取類名稱(去除包名)

/**
 * get short name of given clazz like "Student"
 *
 * @param clazz given clazz
 * @return name String
 */
public static String getClassNameShort(Class<?> clazz) {
    if (clazz == null)
        return "";
    String allName = clazz.getName();
    if (allName == null || allName.isEmpty())
        return "";
    if (!allName.contains("."))
        return allName;
    return allName.substring(allName.lastIndexOf(".") + 1, allName.length());
}

獲取完整類名稱(包含包名)

/**
 * get entire name of given clazz like "java.lang.String"
 *
 * @param clazz given clazz
 * @return name String
 */
public static String getClassNameEntire(Class<?> clazz) {
    if (clazz == null)
        return "";
    return clazz.getName();
}

獲取字段類型 類名稱(去除包名)

/**
 * get short name of given class like "Integer"
 *
 * @param field given field
 * @return name String
 */
public static String getFieldTypeNameShort(Field field) {
    if (field == null)
        return "";
    String allName = field.getType().getName();
    if (allName.isEmpty())
        return "";
    if (!allName.contains("."))
        return allName;
    return allName.substring(allName.lastIndexOf(".") + 1, allName.length());
}

獲取字段類型 類名稱(包含包名)

/**
 * get entire name of given class like "java.lang.Integer"
 *
 * @param field given field
 * @return name String
 */
public static String getFieldTypeNameEntire(Field field) {
    if (field == null)
        return "";
    return field.getType().getName();
}

獲取所有字段

/**
 * get declared fields of given clazz
 *
 * @param clazz given clazz
 * @return list of fields
 */
public static List<Field> getFieldsAll(Class<?> clazz) {
    List<Field> fieldList = new ArrayList<>();
    if (clazz == null)
        return fieldList;
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        fieldList.add(field);
    }
    return fieldList;
}

獲取所有構造器

/**
 * get declared constructors of given clazz
 *
 * @param clazz given clazz
 * @return list of constructors
 */
public static List<Constructor<?>> getConstructorsAll(Class<?> clazz) {
    List<Constructor<?>> constructors = new ArrayList<>();
    if (clazz == null)
        return constructors;
    Constructor<?>[] constructorsArray = clazz.getDeclaredConstructors();
    for (Constructor<?> constructor : constructorsArray) {
        constructors.add(constructor);
    }
    return constructors;
}

字段是否被 public static final 修飾

/**
 * Determine whether the given field is a "public static final *" constant.
 *
 * @param field the field to check
 */
public static boolean isFieldPublicStaticFinal(Field field) {
    int modifiers = field.getModifiers();
    return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
}

字段是否被 static final 修飾

/**
 * Determine whether the given field is a "* static final *" constant.
 *
 * @param field the field to check
 */
public static boolean isFieldStaticFinal(Field field) {
    int modifiers = field.getModifiers();
    return (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
}

字段是否被 static 修飾

/**
 * Determine whether the given field is a "* static *" constant.
 *
 * @param field the field to check
 */
public static boolean isFieldStatic(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isStatic(modifiers);
}

字段是否被 final 修飾

/**
 * Determine whether the given field is a "* final *" constant.
 *
 * @param field the field to check
 */
public static boolean isFieldFinal(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isFinal(modifiers);
}

字段是否被 public 修飾

/**
 * Determine whether the given field is a "public *" constant.
 *
 * @param field the field to check
 */
public static boolean isFieldPublic(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isPublic(modifiers);
}

字段是否被 private 修飾

/**
 * Determine whether the given field is a "private *" constant.
 *
 * @param field the field to check
 */
public static boolean isFieldPrivate(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isPrivate(modifiers);
}

字段是否被 protected 修飾

/**
 * Determine whether the given field is a "protected *" constant.
 *
 * @param field the field to check
 */
public static boolean isFieldProtected(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isProtected(modifiers);
}

構造器是否被 protected 修飾

/**
 * Determine whether the given constructor is a "protected *" constant.
 *
 * @param constructor the field to check
 */
public static boolean isConstructorProtected(Constructor<?> constructor) {
    int modifiers = constructor.getModifiers();
    return Modifier.isProtected(modifiers);
}

構造器是否被 public 修飾

/**
 * Determine whether the given constructor is a "public *" constant.
 *
 * @param constructor the field to check
 */
public static boolean isConstructorPublic(Constructor<?> constructor) {
    int modifiers = constructor.getModifiers();
    return Modifier.isPublic(modifiers);
}

構造器是否被 private 修飾

/**
 * Determine whether the given constructor is a "private *" constant.
 *
 * @param constructor the field to check
 */
public static boolean isConstructorPrivate(Constructor<?> constructor) {
    int modifiers = constructor.getModifiers();
    return Modifier.isPrivate(modifiers);
}    

使字段可以被訪問

/**
 * Make the given field accessible, explicitly setting it accessible if
 * necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 *
 * @param field the field to make accessible
 * @see java.lang.reflect.Field#setAccessible
 */
public static void makeFieldAccessible(Field field) {
    if ((!Modifier.isPublic(field.getModifiers()) ||
            !Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
            Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
        field.setAccessible(true);
    }
}

使構造器可以被訪問

/**
 * Make the given constructor accessible, explicitly setting it accessible
 * if necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 *
 * @param ctor the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
public static void makeConstructorAccessible(Constructor<?> ctor) {
    if ((!Modifier.isPublic(ctor.getModifiers()) ||
            !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
        ctor.setAccessible(true);
    }
}

使方法可以被訪問

/**
 * Make the given constructor accessible, explicitly setting it accessible
 * if necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 *
 * @param ctor the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
public static void makeConstructorAccessible(Constructor<?> ctor) {
    if ((!Modifier.isPublic(ctor.getModifiers()) ||
            !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
        ctor.setAccessible(true);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章