反射获取user类的信息代码
public class Test08 {
public static void main(String[] args) throws Exception, NoSuchFieldException {
// Class c1 = Class.forName("com.reflection.user");
//System.out.println(c1);
//获得对象
user user = new user();
Class c1 = user.getClass();
System.out.println(c1);
System.out.println("===========");
//获得类的名字
System.out.println(c1.getName());//获得包名+类名
System.out.println(c1.getSimpleName());//获得类名
//获得类的属性
Field[] fields = c1.getFields();//只能找到public的属性
fields = c1.getDeclaredFields();//可以获得所有属性值
for (Field field : fields) {
System.out.println(field);
}
//获得指定属性的值
System.out.println("获得指定属性的值");
Field name = c1.getDeclaredField("name");
System.out.println(name);
//获得类的方法
System.out.println("获得类的方法");
Method[] declaredMethods = c1.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println(declaredMethod);
}
Method[] methods = c1.getMethods();
for (Method declaredMethod : methods) {
System.out.print("正常方法:");
System.out.println(declaredMethod);
}
//获得指定方法
//重载
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
//获得构造器
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor : constructors) {
System.out.print("获得正常指定构造器");
System.out.println(constructor);
}
constructors = c1.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.print("获得所有指定构造器");
System.out.println(constructor);
}
//获得指定构造器
Constructor declaredConstructor = c1.getDeclaredConstructor(int.class, int.class, String.class);
System.out.println("指定:"+declaredConstructor);
}
}
user类
public class test01 {
public static void main(String[] args) throws ClassNotFoundException {
//通过反射获取类的class对象
Class c1 = Class.forName("com.reflection.user");
System.out.println(c1);
Class c2 = Class.forName("com.reflection.user");
Class c3 = Class.forName("com.reflection.user");
Class c4 = Class.forName("com.reflection.user");
//一个类在内存中只有一个class对象
//一个类被加载后,类的整个结构都会被封装在class对象中
System.out.println(c2.hashCode());
System.out.println(c3.hashCode());
System.out.println(c4.hashCode());
}
}
//实体类:pojo,entity
class user{
private String name ;
private int id ;
private int age ;
public user() {
}
public user(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "user{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}