1.获取Field
方法 | 作用 |
---|---|
getField(String name) | 返回 字段对象,该对象反映此 类对象表示的类或接口的指定公共成员字段。 |
getFields() | 返回一个包含 字段对象的数组, 字段对象反映此 类对象所表示的类或接口的所有可访问公共成员字段。 |
getDeclaredField(String name) | 返回 字段对象,该对象反映此 类对象表示的类或接口的指定声明字段。 |
getDeclaredFields() | 返回 字段对象的数组, 字段对象反映由此 类对象表示的类或接口声明的所有字段。 |
Studnet.java
package com.sdnu.bean;
public class Student {
public int no;
private String name;
protected int age;
boolean sex;
}
package com.sdnu;
import java.lang.reflect.Field;
public class ReflectDemo4 {
public static void main(String[] args) {
try {
Class studentClass = Class.forName("com.sdnu.bean.Student");
Field[] fields = studentClass.getFields();
System.out.println(fields.length);//1
System.out.println(fields[0].getName());//no
Field[] fs = studentClass.getDeclaredFields();
System.out.println(fs.length);//4
for(Field field : fs) {
System.out.println(field.getName());// no name age sex
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
getModifiers(): 返回的修饰符是一个数字,每一个数字代表一个修饰符。
package com.sdnu;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class ReflectDemo4 {
public static void main(String[] args) {
try {
Class studentClass = Class.forName("com.sdnu.bean.Student");
Field[] fs = studentClass.getDeclaredFields();
for(Field field : fs) {
int modifierNumber = field.getModifiers();
System.out.println(modifierNumber);
System.out.println(Modifier.toString(modifierNumber));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
2.反编译Field
package com.sdnu;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class ReflectDemo5 {
public static void main(String[] args) {
StringBuilder builderString = new StringBuilder();
try {
Class studentClass = Class.forName("com.sdnu.bean.Student");
builderString.append(Modifier.toString(studentClass.getModifiers()));
builderString.append(" class ");
builderString.append(studentClass.getSimpleName());
builderString.append(" " + "{");
builderString.append("\n");
Field[] fields = studentClass.getDeclaredFields();
for(Field fs : fields) {
builderString.append("\t");
builderString.append(Modifier.toString(fs.getModifiers()));
builderString.append(" ");
builderString.append(fs.getType().getSimpleName());
builderString.append(" ");
builderString.append(fs.getName());
builderString.append(";\n");
}
builderString.append("}");
System.out.println(builderString);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
3.通过反射机制访问对象属性
package com.sdnu;
import com.sdnu.bean.Student;
import java.lang.reflect.Field;
public class ReflectDemo6 {
public static void main(String[] args) {
//普通方法
Student student = new Student();
student.no = 2021;
System.out.println(student.no);
//通过反射的机制
try {
//相当于上面方法的 Student student = new Student();
Class studentClass = Class.forName("com.sdnu.bean.Student");
Object obj = studentClass.newInstance();
//相当于上面方法的student.no = 2021;
Field noField = studentClass.getDeclaredField("no");
noField.set(obj, 2021);
System.out.println(noField.get(obj));
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
}
}
两种方式都可以访问对象的属性,但是相比于普通方法,虽然反射机制较为复杂,但是反射机制能够将内容写入配置文件中,较为灵活。
注意:要想访问私有属性,(以上面为例)需要加入下面一行的代码:
noField.setAccessible(true);
4.反射Method
package com.sdnu;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
public class ReflectMethodDemo1 {
public static void main(String[] args) {
try {
Class methodClass = Class.forName("com.sdnu.StudentMethod");
Method[] methods = methodClass.getDeclaredMethods();
for(Method method : methods) {
System.out.println(Modifier.toString(method.getModifiers()));
System.out.println(method.getReturnType().getSimpleName());
System.out.println(method.getName());
Class[] parameterType = method.getParameterTypes();
for(Class parameter : parameterType) {
System.out.println(parameter.getSimpleName());
}
System.out.println("---------------------------------------");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
5.反射机制调用方法
StudentMethod.java
package com.sdnu;
public class StudentMethod {
public int id;
public String userName;
protected int score;
public void setId(int id){
this.id = id;
}
protected String getUserName(){
return userName;
}
public boolean login(String userName, int score){
if(userName != null && score > 60) {
return true;
}
return false;
}
public boolean login(int score){
return false;
}
}
package com.sdnu;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectMethodDemo2 {
public static void main(String[] args) {
try {
Class methodClass = Class.forName("com.sdnu.StudentMethod");
Object obj = methodClass.newInstance();
Method loginMethod = methodClass.getDeclaredMethod("login", String.class, int.class);
Object retValue = loginMethod.invoke(obj, "Jack", 89);
System.out.println(retValue);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
6.反射机制调用构造方法
StudentMethod.java
package com.sdnu;
public class StudentMethod {
public int id;
public String userName;
protected int score;
public StudentMethod() {}
public StudentMethod(int id, String userName, int score) {
this.id = id;
this.userName = userName;
this.score = score;
}
@Override
public String toString() {
return "StudentMethod{" +
"id=" + id +
", userName='" + userName + '\'' +
", score=" + score +
'}';
}
}
ReflectMethodDemo4.java
package com.sdnu;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectMethodDemo4 {
public static void main(String[] args) {
try {
Class studentClass = Class.forName("com.sdnu.StudentMethod");
Object obj = studentClass.newInstance();
Constructor con = studentClass.getDeclaredConstructor(int.class, String.class, int.class);
Object newObj = con.newInstance(12, "Jack", 90);
System.out.println(newObj);
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
7.获取父类和父接口
package com.sdnu;
public class ReflectMethodDemo5 {
public static void main(String[] args) {
try {
Class methodClass = Class.forName("java.lang.String");
//获取String的父类
Class superClass = methodClass.getSuperclass();
System.out.println(superClass.getName());
//获取String的所有接口
Class[] interfaces = methodClass.getInterfaces();
for(Class in : interfaces) {
System.out.println(in.getName());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
作者:Beyong
出处:Beyong博客
github地址:https://github.com/beyong2019
本博客中未标明转载的文章归作者Beyong有,欢迎转载,但未经作者同意必须保留此段声明,且在文章明显位置给出原文连接,否则保留追究法律责任的权利。