Java产生Class类的三种实例化对象的方法
1.object.getClass
2.类名.class直接根据某个具体的类来取得Class实例化对象
3.Class.forName(String className)
public class TestClass {
public static void main(String[] args) {
//1.object.getClass
Date date1 = new Date();
Class cls = date1.getClass();
//java.util.Date
System.out.println("方法1 " + cls.getName());
//class java.util.Date
System.out.println("方法1 " + cls);
//2.类名.class
//一般用类的全限定名
Class cls1 = java.util.Date.class;
//class java.util.Date
System.out.println("方法2 " + cls1);
//3.推荐用
Class cls2 = null;//放在外面可以访问
try {
cls2 = Class.forName("java.util.Date");
System.out.println("方法3 " + cls2);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("比较三个对象");
System.out.println(cls1 == cls);
System.out.println(cls == cls2);
}
}
推荐用第三种,第一种已经new了一个对象了,第二种写的太繁琐了
对象实例化的三种方法
1.new关键字Student student = new Student();
2.反射
(1)Class类的newInstance方法,也是基于Constructor类
(2)java.lang.relect.Constructor类的newInstance方法
public class TestClass1 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//1.getClass()方法
Date date = new Date();
Class cls = date.getClass();
try {
Date date1 = (Date) cls.newInstance();
System.out.println("1 " + date1);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//2.全限定类名.class
Class<java.util.Date> cls2 = java.util.Date.class;
try {
Date date3 = cls2.newInstance();
System.out.println("2 "+date3);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Date date3 = cls2.newInstance();
System.out.println("2 "+date3);
//3.Class.forName方法,大写Class
Class cls1 = Class.forName("java.util.Date");
Object date2 = cls1.newInstance();
System.out.println("3 " + date2);
}
}
以上三种简单写法
1. Student student2 = (Student)Class.forName("Student类全限定名").newInstance();
2. Student stu = Student.class.newInstance();
3. public class Student {
private int id;
public Student(Integer id) {
this.id = id;
}
public static void main(String[] args) throws Exception {
Constructor<Student> constructor = Student.class
.getConstructor(Integer.class);
Student stu3 = constructor.newInstance(123);
}
}
3.clone接口
先实现Cloneable接口,覆写clone方法
Student stu4 = (Student) stu3.clone();
3.反序列化
// 写对象
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("student.bin"));
output.writeObject(stu4);
output.close();
// 读取对象
ObjectInputStream input = new ObjectInputStream(new FileInputStream(
"student.bin"));
Student stu5 = (Student) input.readObject();
System.out.println(stu5);