一、java获取对象的方式
1、通过调用构造函数创建对象
2、匿名对象的创建3、通过在类名前面指定包名来创建指定的对象
4、通过反射机制来创建对象
A、通过调用Class.forName()来获取类名
Lattice lattice=(Lattice) Class.forName("com.lattice.java17_test.Lattice").newInstance();
或
Class classType=Class.forName("com.lattice.java17_test.Lattice");
B、通过调用类名.getClass()来获取类名
com.lattice.java17.Lattice lattice1=new com.lattice.java17.Lattice();
com.lattice.java17.Lattice lattice=lattice1.getClass().newInstance();
C、通过调用类名.class属性来获取类名
com.lattice.java17.Lattice lattice=com.lattice.java17.Lattice.class.newInstance();
D、通过loader()来动态获取类名
Person person=(Person)Proxy.newProxyInstance(Person.class.getClassLoader()
, new Class[]{Person.class}, new Maria(new Peter()));
//获取构造函数列表
Constructor[] constructor=classType.getConstructors();
//获取类属性列表
Field[] field = classType.getFields();
//获取方法wan
Method method=classType.getMethod("wan", null);
method.invoke(lattice, null);
//获取带参数和自定义类做参数的方法
A12 a=new A12();
Method method1=classType.getMethod("play",new Class[]{String.class,int.class,A12.class});
method1.invoke(lattice, new Object[]{"lattice",1,a});
//获取私有方法
Method method3=classType.getDeclaredMethod("test", null);
method3.setAccessible(true);
method3.invoke(lattice, null);
//获取私有属性
Field fieldName1 = classType.getDeclaredField("sex");
fieldName1.setAccessible(true);
String sex=(String) fieldName1.get(lattice);
System.out.println(sex);