本帖最后由 老貓钓鱼 于 2014-4-12 23:50 编辑
这是Person类:
- package com.test;
- import java.io.Serializable;
- public class Person implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = 12345678L;
- /**
- *
- */
-
- private String name;
- private int age;
- Person(String name, int age) {
- setName(name);
- setAge(age);
- }
- public void setName(String name) {
- this.name = name;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return this.name;
- }
- public int getAge() {
- return this.age;
- }
- public boolean equals(Object obj) {
- if(this == obj) {
- return true;
- }
- if(!(obj instanceof Person)) {
- throw new ClassCastException("类型不一致");
- }
- Person per = (Person)obj;
- return this.name.equals(per.name) && this.age == per.age;
- }
- public String toString() {
- return "[name=" + name + ",age=" + age + "]";
- }
- }
复制代码
反射- package com.test;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- public class ReflectDemo {
- public static void main(String[] args) throws SecurityException, NoSuchMethodException, ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
- Class clazz = Class.forName("com.test.Person");
- /*Field[] field = clazz.getDeclaredFields();
- for (Field field2 : field) {
- System.out.println(field2);
- }
- Method[] method = clazz.getDeclaredMethods();
- for (Method method2 : method) {
- System.out.println(method2);
- }
- System.out.println("---------------------");
- Constructor[] con = clazz.getDeclaredConstructors();
- for (Constructor constructor : con) {
- System.out.println(constructor);
- }
- System.out.println("---------------------");
- System.out.println(clazz.getPackage());
- System.out.println("---------------------");*/
-
- //中间的代码我都注释掉了,主要是后面这二句
- Constructor con1 = clazz.getConstructor(String.class, int.class);
- Person p1 = (Person)con1.newInstance(new String("张三"), 21);//实例化对象
- }
- }
复制代码
|