1 获得class对象
public class TestClass {
public static void main(String[] args) throws Exception{
//获得class对象
Class c1=Class.forName("java.lang.String");//必须包名.类名,参数必须
Class c2="".getClass(); //为类型的String
Class c3=int .class;
Class c4= Integer.TYPE;
System.out.println(c1);
System.out.println(c1==c2);
System.out.println(c3==c4);
}
}
2 获得属性 方法
public class TestStudent {
public static void main(String[] args) {
Class c1 = Student.class;
Field[] f1 = c1.getFields();
for (Field ff : f1) {
System.out.println(ff);
}// 没有Declare支持继承,不支持私有
System.out.println("***********");
Field[] f2 = c1.getDeclaredFields();
for (Field ff : f2) {
System.out.println(ff);
}// 有Declare支持不继承,支持私有
System.out.println("***********");
Method[] m1 = c1.getMethods();
for (Method ff : m1) {
System.out.println(ff);
}
System.out.println("***********");
Method[] m2 = c1.getDeclaredMethods();
for (Method ff : m2) {
System.out.println(ff);
}
System.out.println("***********");
try {
Student ss = (Student) c1.newInstance();// 会调用无参数构造
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}// main
}
3 属性 方法 构造的反射
public class Student {
private int age;
public String name;
public Student() {
System.out.println("Student");
}
public Student(int age, String name) {
this.setAge(age);
this.setName(name);
System.out.println("Student(int,String)");
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class TestField {
public static Object getObj (String arg)throws Exception{
Class c1 = Class.forName(arg);
return c1.newInstance();
}
public static void main(String[] args)throws Exception {
Class c1 = Student.class;
Field f=c1.getDeclaredField("age");
Object obj=c1.newInstance();
f.setAccessible(true);//破坏封装
System.out.println(f.get(obj));
f.set(obj, 20);
System.out.println(f.getType());
System.out.println(TestField.getObj("day621xiawu.Student"));
}
}
public class TestConstructor {
public static void main(String[] args) throws Exception{
Class c1 = Student.class;
//用class 做参数
Constructor ct=c1.getConstructor(int.class,String.class);
Object obj = ct.newInstance(23,"zhang");
}
}
public class TestMethod {
public static void main(String[] args) throws Exception{
Class c1 = Student.class;
Method m =c1.getMethod("setAge", int.class);
Object obj = c1.newInstance();
m.invoke(obj, 23);
Student ss=(Student)obj;
System.out.println(ss.getAge());
}
}
4 获得对象填充
public class ObjectFill {
public static Object getInstance(String className, Map<String, Object> map)
throws Exception {
Class c1 = Class.forName(className);
Object obj = c1.newInstance();
Set<String> set = map.keySet();
for (String key : set) {
String mName = "set" + key.substring(0, 1).toUpperCase()
+ key.substring(1);
Field f = c1.getDeclaredField(key);// 通过属性来获得类型
Method m = c1.getMethod(mName, f.getType());
m.invoke(obj, map.get(key));
}
return obj;
}