类加载器
获取Class类对象
反射获取构造方法并使用
案列:反射获取构造方法
public class ReflectDemo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> c = Class.forName("com.wond19.Student");
Constructor<?> con = c.getConstructor(String.class, int.class, String.class);
Object o = con.newInstance("林丹",26,"河南");
System.out.println(o);
}
}
----------------
//Student类
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
//结果
Student{name='林丹', age=26, address='河南'}
构造方法为私有时
public class ReflectDemo {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
Class<?> c = Class.forName("com.wond19.Student");
Constructor<?> con =
c.getDeclaredConstructor(String.class);
//暴力反射,取消访问检查
con.setAccessible(true);
Object o = con.newInstance("林丹");
System.out.println(o);
}
}
反射获取成员变量
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<?> c = Class.forName("com.wond19.Student");
Field address = c.getField("address");
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
address.set(obj,"河南");
System.out.println(obj);
}
-----------------
Student{name='null', age=0, address='河南'}
反射获取成员方法
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
Class<?> c = Class.forName("com.wond19.Student");
Constructor<?> con = c.getConstructor();
Object o = con.newInstance();
Method m1 = c.getMethod("method1");
m1.invoke(o);
Method m2 = c.getMethod("method2", String.class);
m2.invoke(o,"林丹");
Method m3 = c.getMethod("method3", String.class, int.class);
Object o1 = m3.invoke(o, "林丹", 30);
System.out.println(o1);
Method m4 = c.getDeclaredMethod("function");
m4.setAccessible(true);
m4.invoke(o);
}
-------------------
private void function(){
System.out.println("function");
}
public void method1(){
System.out.println("method");
}
public void method2(String s){
System.out.println("method"+s);
}
public String method3(String s,int i){
return s+","+i;
}
----------------
method
method林丹
林丹,30
function
案列: 反射越过泛型检查
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
ArrayList<Integer> array = new ArrayList<>();
Class<? extends ArrayList> c = array.getClass();
Method m = c.getMethod("add", Object.class);
m.invoke(array,"hello");
m.invoke(array,"world");
m.invoke(array,"java");
System.out.println(array);
}
运行配置文件指定内容