class="article_content clearfix">
class="htmledit_views">
常用操作
class="has">package com.test.user;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @Author: xf
* @Date: 2018/5/30 13:52
* @Version 1.0
*/
public class test {
@Test
public void test() throws NoSuchFieldException, IllegalAccessException, InstantiationException, ClassNotFoundException {
Person p = new Person();
Class<Person> personClass = Person.class;//第一种
System.out.println(p.getClass());//第二种
System.out.println("---------------------------");
System.out.println(p.getClass().getName());//获得类的完整名字
System.out.println("-------------获得类的public类型的属性--------------");
//获得类的public类型的属性
Field[] fields = p.getClass().getFields();
for (Field f : fields) {
System.out.println(f.getName());
}
System.out.println("--------------获得类的所有属性。包括私有的和继承类的--------------");
// 获得类的所有属性。包括私有的和继承类的
Field[] allFields = p.getClass().getDeclaredFields();
for (Field field : allFields) {
System.out.println(field.getName());// name age
}
System.out.println("---------------获得类的public类型的方法。这里包括 Object 类的一些方法-------------------------------------");
// 获得类的public类型的方法。这里包括 Object 类的一些方法
Method[] methods = p.getClass().getMethods();
for (Method method : methods) {
System.out.println(method.getName());// work waid equls toString
// hashCode等
}
System.out.println("-------------------获得指定的属性---------------------------------");
// 获得指定的属性
Field f1 = p.getClass().getField("age");
System.out.println(f1);
System.out.println("---------------------------------获得指定的私有属性----------------");
// 获得指定的私有属性
Field f2 = p.getClass().getDeclaredField("name");
// 启用和禁用访问安全检查的开关,值为 true,则表示反射的对象在使用时应该取消 java 语言的访问检查;反之不取消
f2.setAccessible(true);
System.out.println(f2);
System.out.println("-----------------------赋值-----------------------------");
// 创建这个类的一个对象
Object p2 = p.getClass().newInstance();
// 将 p2 对象的 f2 属性赋值为 Bob,f2 属性即为 私有属性 name
f2.set(p2, "Bob");
// 使用反射机制可以打破封装性,导致了java对象的属性不安全。
System.out.println(f2.get(p2)); // Bob
System.out.println("------------------获取构造方法----------------------------------");
// 获取构造方法
Constructor[] constructors = p.getClass().getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor.toString());// public
// com.ys.reflex.Person()
}
// 3、通过 Class 对象的 forName() 静态方法来获取,用的最多,
// 但可能抛出 ClassNotFoundException 异常
Class c3 = Class.forName("com.clkj.xf.app2.Person");
System.out.println(c3);
System.out.println(c3.getName());
}
public class Person {
// 私有属性
private String name = "Tom";
// 公有属性
public int age = 18;
// 构造方法
public Person() {
}
// 私有方法
private void say() {
System.out.println("private say()...");
}
// 公有方法
public void work() {
System.out.println("public work()...");
}
}
}