获取一个类的字节码有三种方法:A、知道类名:类名.class;B、有类的实例p,那么p.getClass();C、基本数据类型装载并且返回字节码:Class.forName("java.lang.String");
总之,只要是在源程序中出现的类型都有Class示例对象。比如:int
A、构造方法反射
获取一个类的所有构造方法:Constructor[] constructor = String.class.getConstructors();
获取一个类里面指定的构造方法:Constructor constructor = String.class.getConstructor(StringBuffer.class);括号内使用了可变参数
String str = constructor.newInstance(new StringBuffer("abc"));
B、成员变量反射(将一个类的String类型成员变量值里面的a换成b)
ReflectPoint point = new ReflectPoint(3,5);
Field[] fields = point.getClass.getFields();
for(Field field:fields){
if(field.getType()==String.class){}
String oldValue =(String) field.get(point);
String newValue = oldValue.replace('a','b');
field.set(point,newValue);
}
C、成员方法反射
Method method = String.class.getMethod("charAt",int.class);
System.out.println(method.invoke(str1,1)); //invoke方法是调用方法对象的方法。假如str1对应的是null,那么调用的是静态方法
package com.day1;
import java.io.FileInputStream; import java.io.InputStream; import java.util.Collection; import java.util.Properties; public class ReflectTest { public static void main(String[] args) throws Exception { //web开发基本用的是这个,eclipse自动将classpath下的文件自动按照目录结构添加到java的.class文件夹下 /** * 使用类加载器加载配置文件 */ InputStream ips0 = ReflectTest.class.getClassLoader().getResourceAsStream("config.properties"); /** * 对于自己这个类来说 * 相对路径,不加/ * 绝对路径,加/ */ //相对于本类的路径来说 InputStream ips1 = ReflectTest.class.getResourceAsStream("sources/config.properties"); //相对于本类的绝对路径来说 InputStream ips2 = ReflectTest.class.getResourceAsStream("/com/day1/sources/config.properties"); //如果需要保存的话,就用这种方式 InputStream ips = new FileInputStream("config.properties"); //InputStream ips = new FileInputStream("src/config.properties"); Properties props = new Properties(); props.load(ips); ips.close(); String className = props.getProperty("className"); Collection col = (Collection)Class.forName(className).newInstance(); ReflectPoint point1 = new ReflectPoint(3, 3); ReflectPoint point2 = new ReflectPoint(3, 5); ReflectPoint point3 = new ReflectPoint(3, 3); //Collection col = new HashSet(); col.add(point1); col.add(point2); col.add(point3); point1.y = 7; col.remove(point1);//其实没有除掉,内存泄露 System.out.println(col.size()); } }