目录
1、类名.class
2、对象.getClass
3、Class.forName (" 权限定名")? 包名+类名???
建立Student测试类
public class Student {
private int age;
private String name;
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
1、类名.class
如:
public class Reflections {
public static void main(String[] args) {
Student s = new Student();
Class cls = Student.class;//类名.class方式获取
Field[] fields = cls.getDeclaredFields();//获取所有类属性
Method[] methods = cls.getDeclaredMethods();//获取所有方法
System.out.println("类名:"+ cls.getName());//获取所有类名
System.out.println("属性:");
for (int i = 0; i < fields.length; i++) {
System.out.println(fields[i].toString());
}
System.out.println("方法名:");
for (int i = 0; i < methods.length; i++) {
System.out.println(methods[i].toString());
}
}
}
?运行结果:
?2、对象.getClass
public class Reflections {
public static void main(String[] args) {
Student s = new Student();
Class cls = s.getClass();//对象.getClass
Field[] fields = cls.getDeclaredFields();//获取所有类属性
Method[] methods = cls.getDeclaredMethods();//获取所有方法
System.out.println("类名:"+ cls.getName());//获取所有类名
System.out.println("属性:");
for (int i = 0; i < fields.length; i++) {
System.out.println(fields[i].toString());
}
System.out.println("方法名:");
for (int i = 0; i < methods.length; i++) {
System.out.println(methods[i].toString());
}
}
}
运行结果:
3、Class.forName (" 权限定名")? 包名+类名???
public class Reflections {
public static void main(String[] args) throws ClassNotFoundException {
Student s = new Student();
Class cls = Class.forName("ttttt.Student");//Class.forName (" 权限定名")?包名+类名??
Field[] fields = cls.getDeclaredFields();//获取所有类属性
Method[] methods = cls.getDeclaredMethods();//获取所有方法
System.out.println("类名:"+ cls.getName());//获取所有类名
System.out.println("属性:");
for (int i = 0; i < fields.length; i++) {
System.out.println(fields[i].toString());
}
System.out.println("方法名:");
for (int i = 0; i < methods.length; i++) {
System.out.println(methods[i].toString());
}
}
}
通过对比三张结果可知没有任何区别
下篇是利用反射机制改变类信息
Java利用反射机制改变对象属性(暴力)_张DD的小铺子的博客-CSDN博客
|