本系列博客汇总在这里:框架基础 汇总
Field 类
Field 类要掌握的方法
代码演示
package cn.wyx.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ReflectDemo4
{
public static void main(String[] args) throws Exception
{
Class<?> class1 = Class.forName("cn.wyx.reflect.Person");
// 获得构造器
Constructor<?> constructor = class1.getDeclaredConstructor(new Class[] {});
// 根据类的默认构造器来获得一个对象
Object instance = constructor.newInstance(new Object[] {});
// 根据方法名字来获得属性对象
Field field = class1.getDeclaredField("name");
// 破坏掉私有属性
field.setAccessible(true);
field.set(instance, "魏宇轩");
// 获得属性的类型
Class<?> type = field.getType();
System.out.println(type);
}
}
package cn.wyx.reflect;
public class Person
{
private Integer id;
private String name;
private String address;
public Person()
{
}
public Person(Integer id, String name, String address)
{
super();
this.id = id;
this.name = name;
this.address = address;
}
private static void printInfo()
{
System.out.println("静态方法的反射调用");
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
@Override
public String toString()
{
return "Person [id=" + id + ", name=" + name + ", address=" + address
+ "]";
}
}
如有错误,欢迎指正!