//动态的创建对象,通过反射 public class Test08 { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { //获得Class对象 Class c1 = Class.forName("com.zwk.reflection.User"); //构造一个对象 User user = (User) c1.newInstance();//本质是调用类的无参构造器 System.out.println(user);
//通过反射操作属性 User user3 = (User) c1.newInstance(); Field name = c1.getDeclaredField("name"); //不能直接操作私有属性, 我们需要关闭程序的安全检测,属性或者方法的setAccessible(true); name.setAccessible(true);// name.set(user3,"李四"); System.out.println(user3.getName()); } } class User{ private String name; private int id; private int age;
public User() { }
public User(String name, int id, int age) { this.name = name; this.id = id; this.age = age; }
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; }
private void test(){
}
@Override public String toString() { return "User{" + "name='" + name + '\'' + ", id=" + id + ", age=" + age + '}'; } }
public class Test { public static void main(String[] args) { User user = new User(101,"张三",18,"男"); User user1 = (User)user.clone();//运用clone()方法产生新对象 System.out.println("user"+user.toString()); System.out.println("user1"+user1.toString());
} } class User implements Cloneable{//被复制的类需要实现Clonenable接口 private int id; private String name; private int age; private String sex;
public Object clone(){//覆盖clone()方法,访问修饰符设为public User user = null; try { user = (User)super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return user; }
/** * java对象的序列化和反序列化 */ public class SerializableTest { public static void main(String[] args) throws Exception { Person zhangsan = new Person(101, "张三", 18, "男"); Person lisi = new Person(102, "李四", 18, "男"); Person xiaohong = new Person(103, "小红", 18, "女");
//反序列化 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser")); Person person1 = (Person) ois.readObject(); Person person2 = (Person) ois.readObject(); Person person3 = (Person) ois.readObject(); System.out.println(person1.toString()); System.out.println(person2.toString()); System.out.println(person3.toString());
ois.close(); ous.close(); } } class Person implements Serializable{//要序列化某个类的对象,这个类必须实现Serializable接口,该接口是个空接口,即该接口中没声明任何方法。 private int id; private String name; private int age; private String sex;