1. Use object.getClass() and class.class to get the Class.
note that getclass() is for objects, .class is for classes, for example, a class Student, a object sy, we call Student.class and sy.getClass.
2.get a class object through forName() method. Like
String className = "java.util.Random";
Class cl = Class.forName(className);
3.then we can creat a instance of that class
Object obj = cl.getConstructor().newInstance();
4.get the structure of a class through its name
java.lang.Class 1.0• Field[] getFields() 1.1• Field[] getDeclaredFields() 1.1getFields returns an array containing Field objects for the public fields of this class or its superclasses; getDeclaredField returns an array of Field objects for all fields of this class. The methods return an array of length 0 if there are no such fields or if the Class objectrepresents a primitive or array type.• Method[] getMethods() 1.1• Method[] getDeclaredMethods() 1.1returns an array containing Method objects: getMethods returns public methods and includes inherited methods; getDeclaredMethods returns all methods of this class or interface but does not include inherited methods.• Constructor[] getConstructors() 1.1• Constructor[] getDeclaredConstructors() 1.1returns an array containing Constructor objects that give you all the public constructors (for getConstructors) or all constructors (for getDeclaredConstructors) of the class represented by this Class object.• isInterface()returns true if this Class object describes an interface.• isEnum() 1.5returns true if this Class object describes an enum.• isRecord() 16returns true if this Class object describes a record.• RecordComponent[] getRecordComponents() 16returns an array of RecordComponent objects that describe the record fields, or null if this class is not a record.• String getPackageName() 9gets the name of the package containing this type, or the package of the element type if this type is an array type, or "java.lang" if this type is a primitive type.
java.lang.reflect.Field 1.1java.lang.reflect.Method 1.1java.lang.reflect.Constructor 1.1• Class getDeclaringClass()returns the Class object for the class that defines this constructor, method, or field.• Class[] getExceptionTypes() (in Constructor and Method classes)returns an array of Class objects that represent the types of the exceptions thrown by the method.• int getModifiers()returns an integer that describes the modifiers of this constructor, method, or field. Use the methods in the Modifier class to analyze the return value.• String getName()returns a string that is the name of the constructor, method, or field.• Class[] getParameterTypes() (in Constructor and Method classes)returns an array of Class objects that represent the types of the parameters.• Class getReturnType() (in Method class)returns a Class object that represents the return type
java.lang.reflect.RecordComponent 16• String getName()Class<?> getType()get the name and type of this record component• Method getAccessor()returns the Method object for accessing this record component
java.lang.reflect.Modifier 1.1• static String toString(int modifiers)returns a string with the modifiers that correspond to the bits set in modifiers.• static boolean isAbstract(int modifiers)• static boolean isFinal(int modifiers)• static boolean isInterface(int modifiers)• static boolean isNative(int modifiers)• static boolean isPrivate(int modifiers)• static boolean isProtected(int modifiers)• static boolean isPublic(int modifiers)• static boolean isStatic(int modifiers)• static boolean isStrict(int modifiers)• static boolean isSynchronized(int modifiers)• static boolean isVolatile(int modifiers)tests the bit in the modifiers value that corresponds to the modifier in the method name.
5.do more
we first get the corresponding Class object. -> Class object
and then call getDeclaredFields on the Class object. -> Field object
then we can use f.get() to get the actual instance field value -> any type value
further more, we can set the value of this field by f.set(obj, value)
for example
var harry = new Employee("Harry Hacker", 50000, 10, 1, 1989);
Class cl = harry.getClass();
// the class object representing Employee
Field f = cl.getDeclaredField("name");
// the name field of the Employee class
Object v = f.get(harry);
// the value of the name field of the harry object, i.e.,
// the String object "Harry Hacker"
but this has violate the rules of encapsulation, for doing this, we need this
f.setAccessible(true); // now OK to call f.get(harry)
but for doing this, we need to add some VM options in our run configuration. Add these
--add-opens java.base/java.util=ALL-UNNAMED--add-opens java.base/java.lang=ALL-UNNAMED
6. get component type of an array
public static Object goodCopyOf(Object a, int newLength) {
Class cl = a.getClass();
if (!cl.isArray()) return null;
Class componentType = cl.getComponentType();
int length = Array.getLength(a);
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
return newArray;
}
7.get and invoke methods
(1) we can get methods through getMethod() using a class object, method name and parameters -> Method object
(2) then we can call method with Object invoke(Object obj, Object... args), obj is the implicit parameter, args are explicit parameters, for example
Method m1 = Employee.class.getMethod("getName");
Method m2 = Employee.class.getMethod("raiseSalary",double.class);
String n = (String) m1.invoke(harry);
double s = (Double) m2.invoke(harry);
本文详细介绍了Java反射机制的使用,包括通过`getClass()`和`.class`获取类对象,使用`forName()`方法,实例化类,获取类的结构如字段、方法、构造器等信息。此外,还讲解了如何违反封装获取和设置实例字段,以及获取数组的组件类型。最后,讨论了如何调用方法和获取方法,并展示了实际操作示例。
322

被折叠的 条评论
为什么被折叠?



