Java反射机制(reflection)使用方法归纳

封装方法归纳

通过反射创建对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* 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

设置对象指定名称字段值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 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

获取对象指定名称的字段值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 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

获取类名称(去除包名)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 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());
}

获取完整类名称(包含包名)

1
2
3
4
5
6
7
8
9
10
11
/**
* 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();
}

获取字段类型 类名称(去除包名)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 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());
}

获取字段类型 类名称(包含包名)

1
2
3
4
5
6
7
8
9
10
11
/**
* 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();
}

获取所有字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 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;
}

获取所有构造器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 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 修饰

1
2
3
4
5
6
7
8
9
/**
* 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 修饰

1
2
3
4
5
6
7
8
9
/**
* 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 修饰

1
2
3
4
5
6
7
8
9
/**
* 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 修饰

1
2
3
4
5
6
7
8
9
/**
* 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 修饰

1
2
3
4
5
6
7
8
9
/**
* 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 修饰

1
2
3
4
5
6
7
8
9
/**
* 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 修饰

1
2
3
4
5
6
7
8
9
/**
* 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 修饰

1
2
3
4
5
6
7
8
9
/**
* 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 修饰

1
2
3
4
5
6
7
8
9
/**
* 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 修饰

1
2
3
4
5
6
7
8
9
/**
* 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);
}

使字段可以被访问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 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);
}
}

使构造器可以被访问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 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);
}
}

使方法可以被访问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 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);
}
}