——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——
1:获取字节码的三种方式: Employee emp=new Employee();
Class clazz1=Employee.class;
Class clazz2=Class.forName(“java.util.HashSet”);
Class clazz3=emp.getClass();
2:通过字节码获取对象:
Employee enp=(Employee) clazz2.newInstance();
3:通过字节码获取字段:
Field [] field=clazz2.getDeclaredFields(); 遍历数组
for(Field f : field) {}
f.setAccessible(true); 允许取私有属性的值
f.type(); 先判断字段的数据类型
f.get(emp); 获取字段的值
f.set(“olaValue”,”newValue”);
4:通过字节码获取方法调用方法:
第一个参数:方法名字 第二个参数:数据类型
Method method=clazz2.getMethod(“main”,String[].class);
执行方法 ,第一个参数,底层方法为静态可以为null,
第二个参数:是执行这个方法所需要的参数
method.invoke(null,new Object[]{“”,”“,”“});
package com.itheima.org1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;
/**
* @author myluo
* 字节码的获取和类型判断
* 反射就是把java类的各个部分映射成新的Java类
*/
public class ReflectTest1 {
public static void main(String[] args) throws Exception {
// reflectMethod1();
// reflevtMethod2();
// reflectMethod3();
// reflectMethod4();
// reflectMethod5(args[0]);
// reflectMethod6();
// reflectArrays();
reflectArrayList();
}
//反射集合,HashSet 不能重复, ArrayList可以重复
private static void reflectArrayList() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
// TODO Auto-generated method stub
//读取配置文件
InputStream is=new FileInputStream(new File("array.properties"));
Properties pro=new Properties();
//把流加载到pro对象
pro.load(is);
is.close();
String className=pro.getProperty("className");
System.out.println(className);
//创建Collection对象
Collection coll=(Collection)Class.forName(className).newInstance();
ReflectPoint a1=new ReflectPoint(1,1);
ReflectPoint a2=new ReflectPoint(5,5);
ReflectPoint a3=new ReflectPoint(1,1);
coll.add(a1);
coll.add(a2);
coll.add(a3);
coll.add(a1);
System.out.println(coll.size());
}
//反射数组clazz.isArray()是否是数组Array.getLength(str);获取数组的长度
private static void reflectArrays() {
// TODO Auto-generated method stub
String [] str=new String[]{"爬山","游泳","跑步"};
// String str="xxxx";
Class clazz= str.getClass();
//判断是否是数组
if(clazz.isArray()){
//获取对象的长度
int len= Array.getLength(str);
for(int i=0;i<len;i++){
//根据对象下标获取数组的值
System.out.println(Array.get(str, i));
}
}else{
System.out.println(str);
}
}
//只要是数组里面是基本数据类型的数组,就不能转换成Object[]数组
private static void reflectMethod6() {
// TODO Auto-generated method stub
int [] a1=new int[]{1,2,3};
int [] a2=new int[2];
int [][]a3=new int [][]{
{1,2,1},
{3,4,5}
};
String [] a4=new String[]{"jack","456"};
//数据类型一样他们的字节码是相等的
System.out.println(a1.getClass()==a2.getClass());
Object obj1=a1;
Object obj2=a2;
Object obj3=a3;
Object obj4=a4;
//只要是数组里面是基本数据类型的数组,就不能转换成Object[]数组
//Object [] objec1=a1; //int.class
//Object [] objec1=a2; //int.class
Object [] objec1=a3; //int[].class
Object [] objec4=a4; //String.class
System.out.println(a1.getClass().getName());
System.out.println(a1.getClass().getSuperclass().getName());
System.out.println(a2.getClass().getSuperclass().getName());
System.out.println(a3.getClass().getSuperclass().getName());
System.out.println(a4.getClass().getSuperclass().getName());
//数组转换成list集合asList
//System.out.println(Arrays.asList(a1));
System.out.println(Arrays.asList(a4));
}
//反射获取方法(其他类的)main方法
private static void reflectMethod5(String args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
// Class clazz= ReflectPoint.class;
// ReflectPoint rp= (ReflectPoint)clazz.newInstance();
// String.class.getMethod(arg0, arg1);
//调用main方法,
// MainReflect.main(new String[]{"123","456","789","555"});
//com.itheima.org1.MainReflect
System.out.println("编译是传进来的包名:"+args);
//根据反射的包名获取字节码,得到method类
Method method= Class.forName(args).getMethod("main", String[].class);
//调用main方法
method.invoke(null, new Object[]{new String[]{"张三","李四","王五"}});
}
//反射修改对象字段的值
private static void reflectMethod4() throws InstantiationException, IllegalAccessException {
// TODO Auto-generated method stub
//加载字节码
Class clazz= ReflectPoint.class;
//获取对象
ReflectPoint rp=(ReflectPoint) clazz.newInstance();
//获取所有字段
Field [] field=clazz.getDeclaredFields();
//遍历数组
for(Field f : field ){
//允许私有
f.setAccessible(true);
if (f.getType()==String.class) {
//获取对象的字段值
System.out.println(f.get(rp));
String str = (String) f.get(rp);
//替换e为A
f.set(rp, str.replace("e", "A"));
System.out.println(f.get(rp));
}
}
System.out.println("=========================");
System.out.println(rp);
}
//反射的字段 ,field
private static void reflectMethod3() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
// TODO Auto-generated method stub
ReflectPoint rp1=new ReflectPoint(5,8);
ReflectPoint rp2=new ReflectPoint(2,3);
//加载字节码
Class clazz=rp1.getClass();
//获取(指定名字)的字段的(公有属性的)属性
Field filedy=clazz.getField("y");
//获取(自定对象)字段的值
Object y= filedy.get(rp1);
System.out.println("y的值="+y);
//获取是有(不管是私有)属性
Field fieldx= clazz.getDeclaredField("x");
//允许获取私有属性的值
fieldx.setAccessible(true);
//获取字段的值
Object x=fieldx.get(rp2);
System.err.println("x的值="+x);
}
//映射Java类中构造函数
private static void reflevtMethod2() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
//加载字节码
Class clazz= String.class;
//获取指定类型(StringBuffered)构造函数
Constructor constructor=clazz.getConstructor(StringBuffer.class);
//根据构造函数获取对象
String str= (String) constructor.newInstance(new StringBuffer("abc"));
//打印一下对象
System.out.println(str.charAt(1));
}
//字节码的三种创建方式
private static void reflectMethod1()
throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
String str1="abc";
//字节码一
Class clazz1=str1.getClass();
//字节码二
Class clazz2=String.class;
//字节码三
Class clazz3= Class.forName("java.lang.String");
//true
System.out.println(clazz1==clazz2);
//true
System.out.println(clazz1==clazz3);
//判断是否是基本数据类型 false
System.out.println(clazz1.isPrimitive());
//判断int是否是基本数据类型 true
System.out.println(int.class.isPrimitive());
//判断int字节码是否和Integer字节码是否相等,false
System.out.println(int.class==Integer.class);
//判断int类型是否等于Integer的类型 ,true
System.out.println(int.class==Integer.TYPE);
//判断数组是否是基本数据类型,false
System.out.println(int[].class.isPrimitive());
//判断是否是数组,true
System.out.println(int[].class.isArray());
//获取方法
Method method= String.class.getMethod("charAt", int.class);
System.out.println("method="+method.invoke(str1, 2));
}
}
class MainReflect {
public static void main(String[] args) {
for(String str : args){
System.out.println(str);
}
}
}
//反射的类
class ReflectPoint {
private int x;
public int y;
public String str1="itheima";
public String str2="reflect";
public String str3="red";
public ReflectPoint(int x, int y) {
this.x = x;
this.y = y;
}
public ReflectPoint() {
super();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
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;
}
public String toString(){
return "str1="+str1+"str2="+str2+"str3="+str3;
}
}
原文地址:http://blog.csdn.net/myadmini/article/details/45971289