newInstance():创建此 Class 对象所表示的类的一个新实例。
import java.lang.reflect.*;
public class ReflectTest {
public static void main(String[] args) throws Exception {
String str1="abc";
Class cls1=str1.getClass();
Class cls2=String.class;
Class cls3=Class.forName("java.lang.String");
System.out.println(cls1==cls2);
System.out.println(cls3==cls2);
System.out.println(cls1.isPrimitive());
System.out.println(int.class.isPrimitive());
System.out.println(int.class==Integer.class);
System.out.println(int.class==Integer.TYPE);
System.out.println(int[].class.isPrimitive());
System.out.println(int[].class.isArray());
Constructor<String> constructor1=String.class.getConstructor(StringBuffer.class);
String str2=constructor1.newInstance(new StringBuffer("abc"));
System.out.println(str2.charAt(2));
}
}
import java.lang.reflect.*;
public class ReflectTest {
public static void main(String[] args) throws Exception {
String str1="abc";
Class cls1=str1.getClass();
Class cls2=String.class;
Class cls3=Class.forName("java.lang.String");
}
}
import java.lang.reflect.*;
public class ReflectTest {
public static void main(String[] args) throws Exception {
Constructor<String> constructor1=String.class.getConstructor(StringBuffer.class);//获得构造方法
String str2=constructor1.newInstance(new StringBuffer("abc"));//实例化对象
System.out.println(str2.charAt(2));
}
}
Field getField(String s):只能获取公有和父类中公有。
Field getDeclaredField(String s):获取该类中任意成员变量,包括私有。
setAccessible(ture):如果是私有字段,要先将该私有字段进行取消权限检查的能力。也称暴力访问。
set(Object obj, Object value):将指定对象变量上此Field对象表示的字段设置为指定的新值。
Object get(Object obj):返回指定对象上Field表示的字段的值。
代码示例:
import java.lang.reflect.*;
public class ReflectTest {
public static void main(String[] args) throws Exception {
ReflectPoint pt1=new ReflectPoint(3,5);
Field fieldY=pt1.getClass().getField("y");
Field fieldX=pt1.getClass().getDeclaredField("x");
fieldX.setAccessible(true);
System.out.println(fieldY.get(pt1));
System.out.println(fieldX.get(pt1));
System.out.println(pt1);
changStringValue(pt1);
System.out.println(pt1);
}
private static void changStringValue(Object obj) throws IllegalArgumentException, IllegalAccessException {
Field[] fields=obj.getClass().getFields();
for(Field field:fields){
if(field.getType()==String.class){
String oldValue=(String) field.get(obj);
String newValue=oldValue.replace("b", "a");
field.set(obj, newValue);
}
}
}
}
public class ReflectPoint {
private int x;
public int y;
public String str1="gbadb";
public String str2="abbbd";
public String str3="aaaag";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
public String toString() {
return str1+":"+str2+":"+str3;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
五、Method
1、 Method类:代表某个类(字节码)中的成员方法。
2、 主要方法:
Method[] getMethods():只获取公共和父类中的方法。
Method[] getDeclaredMethods():获取本类中包含私有。
Method getMethod("方法名",参数.class(如果是空参可以写null)):获得方法
Object invoke(Object obj ,参数):调用方法, 如果方法是静态,invoke方法中的对象参数可以为null。
代码示例:
import java.lang.reflect.*;
public class ReflectTest {
public static void main(String[] args) throws Exception {
String str1="abc";
Method methodCharAt=String.class.getMethod("charAt", int.class);
System.out.println(methodCharAt.invoke(str1, 1));
System.out.println(methodCharAt.invoke(str1, new Object[]{2}));
String startingClassName=args[0];
Method mainMethod=Class.forName(startingClassName).getMethod("main", String[].class);
mainMethod.invoke(null, new Object[]{new String[]{"111","222","333"}});
}
}
六、数组的反射
1、 具有相同维数和元素类型的数组属于同一个类型,即具有相同的 Class 实例对象。
2、 代表数组的Class实例对象的 getSuperClass()方法返回的父类为Object 类对应的 Class。
3、基本类型的一维数组可以被当作Object 类型使用,不能当作Object[]类型使用;非基本类型的一维数组,既可以当做Object 类型使用,又可以当做Object[]类型使用。
177 / 196
4、 Arrays.asList()方法处理 int[]和 String[]时的差异:int[]得到的是元素的哈希地址值 String[]得到的是数组元素。
5、 Array工具类用于完成对数组的反射操作。
代码示例:
import java.lang.reflect.*;
public class ReflectTest {
public static void main(String[] args) throws Exception {
int[] a1=new int[]{1,2,3};
int[] a2=new int[4];
int[][] a3=new int[2][3];
String[] a4=new String[]{"a","b","c"};
System.out.println(a1.getClass()==a2.getClass());
// System.out.println(a1.getClass()==a3.getClass());
// System.out.println(a1.getClass()==a4.getClass());
System.out.println(a1.getClass().getName());
System.out.println(a1.getClass().getSuperclass().getName());
System.out.println(a2.getClass().getSuperclass().getName());
printObject(a1);
printObject(a4);
}
private static void printObject(Object obj) {
Class cls=obj.getClass();
if(cls.isArray()){
int len=Array.getLength(obj);
for(int i=0;i<len;i++){
System.out.println(Array.get(obj, i));
}
}else{
System.out.println(obj);
}
}
}
七、反射的作用——实现框架的功能
1、 框架:通过反射调用Java类的一种方式。
如房地产商造房子用户住,门窗和空调等等内部都是由用户自己安装,房子就是框架,用户需使用此框架,安好门窗等放入到房地产商提供的框架中。
框架和工具类的区别:工具类被用户类调用,而框架是调用用户提供的类。
2、 框架机器要解决的核心问题:
我们在写框架(造房子的过程)的时候,调用的类(安装的门窗等)还未出现,那么,框架无法知道要被调用的类名,所以在程序中无法直接new其某个类的实例对象,而要用反射来做。
3、 简单框架程序的步骤:
(1)右击项目File命名一个配置文件如:config.properties,然后写入配置信息。如键值对:className=java.util.ArrayList,等号右边的配置键,右边是值。
(2)代码实现,加载此文件:
①将文件读取到读取流中,要写出配置文件的绝对路径。
如:InputStream is=new FileInputStream(“配置文件”);
②用Properties类的load()方法将流中的数据存入集合。
③关闭流:关闭的是读取流,因为流中的数据已经加载进内存。
(3)通过getProperty()方法获取className,即配置的值,也就是某个类名。
(4)用反射的方式,创建对象newInstance()。
(5)执行程序主体功能。
代码示例:
import java.io.*;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Properties;
public class ReflectTest2 {
public static void main(String[] args) throws Exception {
InputStream ips=new FileInputStream("config.properties");
Properties prop=new Properties();
prop.load(ips);
ips.close();
String className=prop.getProperty("className");
Collection collections=(Collection) Class.forName(className).newInstance();
// Collection collections=new HashSet();
ReflectPoint pt1=new ReflectPoint(3,3);
ReflectPoint pt2=new ReflectPoint(5,5);
ReflectPoint pt3=new ReflectPoint(3,3);
collections.add(pt1);
collections.add(pt2);
collections.add(pt3);
collections.add(pt1);
System.out.println(collections.size());
}
}
public class ReflectPoint {
private int x;
public int y;
public String str1="gbadb";
public String str2="abbbd";
public String str3="aaaag";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
public String toString() {
return str1+":"+str2+":"+str3;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}