各种反射
类构造函数反射
import java.lang.reflect.Constructor;
public class reflectConstructor {
/**
* @param args
* @throws Exception
* @throws NoSuchMethodException
*/
public static void main(String[] args) throws NoSuchMethodException, Exception {
// TODO Auto-generated method stub
char[] c = {'a','b','c'};
String s = new String(c,0,c.length);
System.out.println(s);
Constructor cons = String.class.getConstructor(char[].class,int.class,int.class);
System.out.println(cons.newInstance(c,0,c.length));
}
}
类成员反射
//通过反射机制来修改属性的值. 把b改成a.
import java.lang.reflect.Field;
import java.util.ArrayList;
public class repleaceBtoA {
/**
* @param args
* @author liuyue
* @throws Exception
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws IllegalArgumentException, Exception {
// TODO Auto-generated method stub
fieldDemoInB fd = new fieldDemoInB();
System.out.println("最初的值: "+fd.s1+" "+fd.s2+" "+fd.s3+" "+fd.s4);
bToa(fd);
System.out.println("改后的值: "+fd.s1+" "+fd.s2+" "+fd.s3+" "+fd.s4);
}
static void bToa(fieldDemoInB fd) throws Exception{
Field[] fs = fd.getClass().getDeclaredFields(); //获取fieldDemoInB类中所有的属性(包括private的)
for(Field f:fs){ //循环遍历属性
f.setAccessible(true); //设置属性为可操作
// if(f.get(fd).getClass().equals(String.class)){ //这句是小重点, 判断属性是否是String类型
if(f.getType()==String.class){ //看了答案后, 发现更好的判断方式是这样, 但是上边那句仍然可以达成目的.
String s = (String) f.get(fd);
f.set(fd, s.replace('b', 'a'));
}
}
}
/***这都是一坨屎, 别管这个------------------------------------------------
//为了整洁, 把修改的代码写到一个方法里
static void bToa(fieldDemoInB fd) throws Exception{
Field[] fs = fd.getClass().getDeclaredFields(); //获取fieldDemoInB类中所有的属性(包括private的)
ArrayList<Field> alf = new ArrayList<Field>(); //建立一个数组等着存放符合条件的属性
for(Field f:fs){ //循环遍历属性
f.setAccessible(true); //设置属性为可操作
// if(f.get(fd).getClass().equals(String.class)){ //这句是小重点, 判断属性是否是String类型
if(f.getType()==String.class){ //看了答案后, 发现更好的判断方式是这样, 但是上边那句仍然可以达成目的.
alf.add(f); //是String则存到数组中
}
}
for(Field f:alf){ //遍历数组中的所有元素
String s = (String) f.get(fd);
StringBuffer sb = new StringBuffer(s);
for(int i = 0;i<sb.length();i++){ // 遍历属性内的值
if(sb.charAt(i)=='b'){ //判断值是否包含小写b
sb.setCharAt(i, 'a'); //小写b替换为小写a
f.set(fd, sb.toString()); //把替换完的字符串赋值给fd中的属性. 到此就完成了修改.
}
}
}
}
-------------------------------------------------------***/
}
//等待被修改的类, 没什么好说的, 出生就是为了被修改.
class fieldDemoInB{
private int x = 24;
public int y = 25;
public String s1 = "ball_1";
public String s2 = "ball_2";
public String s3 = "ball_3";
public String s4 = "meiyou";
public fieldDemoInB() {
super();
}
}
类方法反射
import java.lang.reflect.Method;
public class reflectMethod {
/**
* @param args
* @throws Exception
* @throws NoSuchMethodException
*/
public static void main(String[] args) throws NoSuchMethodException, Exception {
// TODO Auto-generated method stub
//用反射机制来运行String.CharAt()
String s = "abc";
System.out.println(s.charAt(0));
Method m = String.class.getMethod("charAt", int.class);
System.out.println(m.invoke(s, 0));
}
}
数组的反射
import java.lang.reflect.Array;
public class reflectArray {
/**
* @param args
* @author liuyue
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] i = new int[]{1,2,3,4,5};
String[] s = new String[]{"a","b","c","d","e"};
printArray(i);
printArray(s);
}
private static void printArray(Object obj) {
// TODO Auto-generated method stub
if(obj.getClass().isArray()){ //判断obj是不是数组, 是就循环打印, 不是就直接打印
for(int i=0;i<Array.getLength(obj);i++){ // Array.getLength(obj)来获取数组长度
System.out.println(Array.get(obj, i)+" "); // Array.get(array, index)来返回数组(array)中指定下标(index)的值
}
}
else{
System.out.println(obj);
}
}
}
使用反射机制访问对象属性
package com.basicUp2;
import java.beans.BeanDescriptor;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class beanDemo1 {
public static void main(String[] args) throws Exception{
rp s1 = new rp();
/*这是用过调用方法来对类进行操作-----
s1.setX(10);
s1.setY(9);
int sum = s1.getSum();
System.out.println(sum);
----------------------------------*/
//OK, 然后用反射机制对类进行操作
//首先是比较笨拙的方法
String propertyName = "x";
//
// BeanInfo bi = Introspector.getBeanInfo(s1.getClass()); // 通过BeanInfo的IntroSpector.getBeanInfo()方法来获取s1的BeanInfo
// PropertyDescriptor[] pds = bi.getPropertyDescriptors(); // 之所以说笨拙, 就是因为这种方法只能返回所有的PropertyDescriptor, 然后再遍历
// for (PropertyDescriptor pd : pds){ // 就是这样, 遍历判断每一个返回结果是不是想要的那个
// if(pd.getName().equals(propertyName)){
// Method setVlaue = pd.getWriteMethod();
// setVlaue.invoke(s1,15);
// Method returnValue = pd.getReadMethod();
// Object or = returnValue.invoke(s1);
// System.out.println(or); // 这个的打印结果是15
// }
// }
//下边是简便的方法, 可以直接得到想要的那一个, 而不是所有的.
setProperty(s1, propertyName, 20);
Object ox = getProperty(s1, propertyName);
System.out.println(ox); // 这个的打印结果是20
}
private static Object getProperty(rp s1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(propertyName, s1.getClass());
Method returnXvalue = pd.getReadMethod(); //通过PropertyDescriptor的getReadMethod()来获取s1的getX()方法
Object ox = returnXvalue.invoke(s1);
return ox;
}
private static void setProperty(Object s1, String propertyName, int i)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(propertyName, s1.getClass());
Method setXvlaue = pd.getWriteMethod(); //通过PropertyDescriptor的getWriteMethod()来获取s1的setX()方法
setXvlaue.invoke(s1, i);
}
}
class rp{
private int x,y;
rp(){
}
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getSum(){
return x+y;
}
}