java反射测试代码!枚举测试,beanUtils测试等….挺有用的。。。
完整通过反射自定义框架请看别一个博客:http://blog.csdn.net/liangrui1988/article/details/9348299
jjava加强课程测试代码 反射、 代理 、泛型、beanUtils等 项目源码下载:http://download.csdn.net/detail/liangrui1988/6568169
部分代码:
package com.zhang.test;import java.lang.reflect.Method;public class MethodTest {public static void main(String[] args) throws Exception {System.out.println("hello....");//参数,类完整路径String startClassName=args[0];//startClassName="com.zhang.test.TestReflect";//获得startClassName方法 mainMethod method=Class.forName(startClassName).getMethod("main",String[].class);//调用方法method.invoke(null, new Object[]{new String[]{"123","3333"}});}}//class TestReflect{public static void main(String[] args){for(String a:args){System.out.println(a);}}}
package com.zhang.test;import java.lang.reflect.Method;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.ArrayList;import java.util.Date;import java.util.List;public class GenericityTest {public static void main(String[] args) throws SecurityException, NoSuchMethodException {Beans be=new Beans();List<Beans> list=new ArrayList<Beans>();//能过反射获原方法,Method m=GenericityTest.class.getMethod("getGenricType", List.class,Date.class);//获取方法泛型内型Type[] t=m.getGenericParameterTypes();//获取第一个参数 内型 ParameterizedType p =(ParameterizedType) t[0];//获取方法参数原生内型 (集合) System.out.println(p.getRawType());//获取集合泛型的内型 System.out.println(p.getActualTypeArguments()[0]); //得到参数内型中的泛型内型 Type type= p.getActualTypeArguments()[0]; System.out.println(be.getClass()); //通过反射获取的集合泛集内型和对象内型比较,是一样的 if(be.getClass()==type){ System.out.println("======"); } }public void getGenricType(List<Beans> list,Date d){}public void getGenricType2(Date d){}}
package com.zhang.test;public class HashCodeTest {String x="aq";String y="bb";int xx;int yy;public static void main(String[] args) {}public HashCodeTest(int xx, int yy) {this.xx = xx;this.yy = yy;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((x == null) ? 0 : x.hashCode());result = prime * result + xx;System.out.println("result:"+result);return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;HashCodeTest other = (HashCodeTest) obj;if (x == null) {if (other.x != null)return false;} else if (!x.equals(other.x))return false;if (xx != other.xx)return false;return true;}public String getX() {return x;}public void setX(String x) {this.x = x;}public String getY() {return y;}public void setY(String y) {this.y = y;}public int getXx() {return xx;}public void setXx(int xx) {this.xx = xx;}public int getYy() {return yy;}public void setYy(int yy) {this.yy = yy;}}
package com.zhang.test;import java.util.Collection;import java.util.HashSet;public class HashMian {public static void main(String[] args) {HashCodeTest h1=new HashCodeTest(2,3);HashCodeTest h3=new HashCodeTest(6,7);HashCodeTest h4=new HashCodeTest(6,7);Collection c=new HashSet();c.add(h1);c.add(h3);c.add(h4); c.add(h1); //没有实现hashCode就等于3 因为他把HashSet分了若干个区//当值去做比较时,他是相据hashCode算出区找值比较,发现没有就存下来了System.out.println(c.size()); //实现hashCode 当值发生改变时,集合不会删掉 //因为在删除时它去找hashCode的值,发现没有了(h1已改变) //会造成内存泄露 h1.xx=100; c.remove(h1); System.out.println(c.size());}}
package com.zhang.test;import java.beans.PropertyDescriptor;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import java.lang.reflect.Method;import java.util.Map.Entry;import java.util.Properties;public class LoadProperties {public static void main(String [] args) throws Exception {// TODO Auto-generated method stubInputStream is=new FileInputStream("config.properties"); //k=v 集合Properties pt=new Properties();//加载文件 得到集合中pt.load(is);is.close();for(Entry e:pt.entrySet()){System.out.println(e.getKey()+": "+e.getValue());} System.out.println("key1: ="+pt.get("key1")); //加载文件 到流中 在class目录下 查找你要加载的文件 // InputStream ips= LoadProperties.class.getClassLoader().getResourceAsStream("com/zhang/test/config.properties"); //相对路径中查找文件 InputStream ips= LoadProperties.class.getResourceAsStream("config.properties");Properties pt2=new Properties();//加载文件 得到集合中pt2.load(ips); System.out.println("key2: ="+pt2.get("key2")); //内省 获取属性的方法 读取值 HashCodeTest hct=new HashCodeTest(5,6); String field="xx"; //字段 》 对象字节码 PropertyDescriptor pd=new PropertyDescriptor(field,hct.getClass()); Method m=pd.getReadMethod();//只读方法 Object reflctValue=m.invoke(hct);//调用 对象中的方法 //获得方法返回结果 System.out.println(reflctValue); //获取xx写的方法 Method m2=pd.getWriteMethod(); m2.invoke(hct, 88); System.out.println(hct.getXx()); }}
//枚举测试
package com.emun.test;public abstract class WeekDay {private WeekDay(){}//内部类实现public final static WeekDay SUN=new WeekDay(){//重写父类的方法@Overridepublic WeekDay nextWeekDay() {return MON;}}; public final static WeekDay MON=new WeekDay(){ //重写父类的方法@Overridepublic WeekDay nextWeekDay() {// TODO Auto-generated method stubreturn SUN;} }; //抽象方法 public abstract WeekDay nextWeekDay(); /* public WeekDay nextWeekDay(){ if(this==SUN){ return MON; } else if(this==MON){ return SUN; }else{ return null; } }*/ //覆盖toString public String toString(){ //如果对象为sun 就转换为字符串 return this==SUN?"SUN":"MON"; } // 内部类 枚举,红,绿,黄,灯 public enum TrafficLamp{ RED{ //内部类重写父类的抽像方法@Overridepublic TrafficLamp nextLamp() {//红灯下一个是绿灯return GREEN;} }, GREEN{@Overridepublic TrafficLamp nextLamp() {// TODO Auto-generated method stubreturn YELLOW;} }, YELLOW{@Overridepublic TrafficLamp nextLamp() {// TODO Auto-generated method stubreturn RED;} }; //下一个灯 public abstract TrafficLamp nextLamp(); } }
package com.emun.test;public class WeekdayTest {public static void main(String [] args) {System.out.println("下一个是:"+WeekDay.MON.nextWeekDay());System.out.println("绿灯下一个是:"+WeekDay.TrafficLamp.GREEN.nextLamp());}}
beanUtils测试:
beanUtils jar下载地址:http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi
package com.beanUtilsTest;import java.lang.reflect.Field;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.PropertyUtils;import com.zhang.test.Beans;public class BeanUtilsTest {public static void main(String[] args) throws Exception{Beans bean=new Beans();bean.setName("dd");System.out.println(bean.getClass());//BeanUtils获得对象的值 String s=BeanUtils.getProperty(bean, "name");System.out.println(s);//BeanUtils设值对象的值 都 以String内型BeanUtils.setProperty(bean, "id",88);System.out.println("id:"+bean.getId());//必须是原始内型PropertyUtils.setProperty(bean, "id","99");System.out.println("id:"+bean.getId());//设置map值Beans beanMap=new Beans();Map<String,String> map=new HashMap<String,String>();/*map.put("id", "66");map.put("name","hello");*/BeanUtils.setProperty(map, "id", "55");BeanUtils.setProperty(map, "name", "hello");//读取mapIterator i=map.keySet().iterator();while(i.hasNext()){System.out.println("i:"+map.get(i.next()));}//方式二for(Entry<String,String> e:map.entrySet()){System.out.println("方式二k:"+e.getKey());System.out.println("方式二v:"+e.getValue());}//把map转为beanBeanUtils.populate(beanMap, map);System.out.println("beanMap:"+beanMap.getId()+"\t"+beanMap.getName());//把bean转为map//Map m=BeanUtils.describe(bean);//=================================================================/** * 基本内型 * double,float,int,short,boolean,byte,char,long * *///获得对象 Object obj=bean.getClass().newInstance(); //反射得到字段 Field s2=bean.getClass().getDeclaredField("name"); s2.setAccessible(true); //设值 Object value="小明"; //获得字段的内型 String fType=s2.getType().getSimpleName(); System.out.println("fType:"+fType); //如是都 是String if(fType.equals("String")){ if(value instanceof String){ s2.set(obj, value); } //如是其它的这样需转换 if(value instanceof Long){ s2.set(obj, value.toString()); } } //其它类型都需这样判断。。。。。。。。 Beans reBeans=(Beans) obj; System.out.println("通过反射对对象成功设值: "+reBeans.getName()); }}
//代理测试
package com.proxyTest;import java.lang.reflect.Constructor;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.sql.Connection;public class ProxyTest {public static void main(String[] args) {//获取代理字节码Class clazzProxy=Proxy.getProxyClass(Connection.class.getClassLoader(),Connection.class);System.out.println(clazzProxy.getName());System.out.println("-----------Proxy构造方法列表------------");Constructor[] constructor=clazzProxy.getConstructors();for(Constructor con:constructor){//get名称String conName=con.getName();//接接参数StringBuilder sb=new StringBuilder(conName);//单线程 快 sb.append('(');//get 获得参数类型的字节码Class[] paraClass=con.getParameterTypes();for(Class c:paraClass){//获取参数sb.append(c.getName()).append(',');}if(paraClass!=null&?Class.length!=0)sb.deleteCharAt(sb.length()-1);sb.append(')');System.out.println(sb.toString());}System.out.println("\n================Proxy方法列表=============================");Method[] methods=clazzProxy.getMethods();for(Method me:methods){//get名称String conName=me.getName();//接接参数StringBuilder sb=new StringBuilder(conName);//单线程 快 sb.append('(');//get 获得参数类型的字节码Class[] paraClass=me.getParameterTypes();for(Class c:paraClass){//获取参数sb.append(c.getName()).append(',');}if(paraClass!=null&?Class.length!=0)sb.deleteCharAt(sb.length()-1);sb.append(')');System.out.println(sb.toString());}}}
才能做到人在旅途,感悟人生,享受人生。