1.ArrayList list = new ArrayList();
这个泛型为Integer的ArrayList中存放一个String类型的对象
package com.itheima.tests;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
/*
* 1.ArrayList<Integer> list = new ArrayList<Integer>();
为这个泛型为Integer的ArrayList中存放一个String类型的对象
*/
public class Test01 {
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
System.out.println(list);
//通过反射获取ArrayList集合的字节码对象
Class clazz = Class.forName("java.util.ArrayList");
//通过反射获取add方法
Method addMethod = clazz.getMethod("add", Object.class);
//通过反射调用addMethod方法
addMethod.invoke(list, "reflect is very good!");
System.out.println(list);
// HashMap<Integer,Integer> hm = new HashMap<>();
}
}
2.用反射去创建一个对象,有2种方式,尽量用代码去体现
package com.itheima.tests;
import java.lang.reflect.Constructor;
/**
* 2.用反射去创建一个对象,有2种方式,尽量用代码去体现
* @author JX
*
*/
public class Test02 {
public static void main(String[] args) throws Exception {
//获取Student类的字节码对象
Class clazz = Class.forName("com.itheima.tests.Student");
//1.利用反射创建一个空的对象
Student student = (Student)clazz.newInstance();
/*//2.获取字段
Field ageField = clazz.getDeclaredField("age");
Field nameField = clazz.getDeclaredField("name");
//取出私有属性
ageField.setAccessible(true);
nameField.setAccessible(true);
//3.给字段设置值
ageField.set(student, 30);
nameField.set(student, "张三");
System.out.println(student);*/
/*Method setAgeMethod = clazz.getMethod("setAge", int.class);
Method setNameMethod = clazz.getMethod("setName", String.class);
setAgeMethod.invoke(student, 38);
setNameMethod.invoke(student, "柳岩");
System.out.println(student);*/
//获取有参构造
Constructor constructor = clazz.getConstructor(int.class,String.class);