编写一个类,增加一个实例方法用于打印一条字符串。
Scanner input=new Scanner(System.in);
Class aClass = Class.forName("HW2.Dog");
Method write = aClass.getMethod("write", String.class);//调出write方法,后面是方法的参数
System.out.println("input a message");
String s = input.next();
Object wowowowo = write.invoke(aClass, s);//运行该方法,s为输入的值
反射修改属性
import java.lang.reflect.Field;
public class Test1 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
/*6.
使用反射的方式创建一个实例、调用构造函数初始化name、love,使用反射方式调用setName方法对名称进行设置,
不使用setAge方法直接使用反射方式对age赋值。*/
Class class1=Class.forName("HW2.Dog");
Dog dog=(Dog)class1.newInstance();
Field name = class1.getField("name");
name.set(dog,"nono");//给dog对象的name属性赋值,直接诶使用反射方式对age赋值
dog.name="nono";//调用构造函数初始化name、love
dog.setLove("eat");
System.out.println(dog);
}
}
泛型为Integer的ArrayList中存放一个String类型的对象
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
/*1.ArrayList<Integer> list = new ArrayList<Integer>();
这个泛型为Integer的ArrayList中存放一个String类型的对象*/
ArrayList<Integer> list=new ArrayList<>();
Class clazz=list.getClass();//通过反射建立一个对象,进行了一个翻墙,即不通过Interger的限制可以向对象中添加元素
Method add = clazz.getMethod("add", Object.class);//调出add方法
Object lalala = add.invoke(list, "lalala");//通过invoke调用方法,add方法的功能是添加想要添加的字符串,但是
//在原来的集合中无法直接添加字符串类型,所以使用反射建立对象添加。
System.out.println(list);
}
}