publicclassUser{privateint id;privateint age;private String name;/**
* @return the id
*/publicintgetId(){return id;}/**
* @param id the id to set
*/publicvoidsetId(int id){this.id = id;}/**
* @return the age
*/publicintgetAge(){return age;}/**
* @param age the age to set
*/publicvoidsetAge(int age){this.age = age;}/**
* @return the name
*/public String getName(){return name;}/**
* @param name the name to set
*/publicvoidsetName(String name){this.name = name;}publicUser(int id,int age, String name){super();this.id = id;this.age = age;this.name = name;}publicUser(){super();}
publicclassDemo05{publicstaticvoidmain(String[] args){try{
Class clazz= Class.forName("demo.shiwen.test.annotation.SxtStudent");//获得类的所有有效注解
Annotation[] annotations=clazz.getAnnotations();for(Annotation a : annotations){
System.out.println(a);}//获得类的指定的注解
SxtTable st =(SxtTable) clazz.getAnnotation(SxtTable.class);
System.out.println(st.value());//获得类的属性的注解
Field f = clazz.getDeclaredField("studentName");
SxtField sxtField = f.getAnnotation(SxtField.class);
System.out.println(sxtField.columnName()+"--"+sxtField.type()+"--"+sxtField.length());}catch(Exception e){
e.printStackTrace();}}}
7 通过跳过安全检查,提高反射效率(三种执行方法的效率差异比较)
publicclassDemo06{publicstaticvoidtest01(){
User u =newUser();long startTime = System.currentTimeMillis();for(int i =0; i <1000000000L; i++){
u.getName();}long endTime = System.currentTimeMillis();
System.out.println("普通方法调用,执行10亿次,耗时:"+(endTime-startTime)+"ms");}publicstaticvoidtest02()throws Exception{
User u =newUser();
Class clazz= u.getClass();
Method m = clazz.getDeclaredMethod("getName", null);// m.setAccessible(true);long startTime = System.currentTimeMillis();for(int i =0; i <1000000000L; i++){
m.invoke(u, null);}long endTime = System.currentTimeMillis();
System.out.println("反射动态方法调用,执行10亿次,耗时:"+(endTime-startTime)+"ms");}publicstaticvoidtest03()throws Exception{
User u =newUser();
Class clazz= u.getClass();
Method m = clazz.getDeclaredMethod("getName", null);
m.setAccessible(true);//不需要执行访问安全检查long startTime = System.currentTimeMillis();for(int i =0; i <1000000000L; i++){
m.invoke(u, null);}long endTime = System.currentTimeMillis();
System.out.println("反射动态方法调用,跳过安全检查,执行10亿次,耗时:"+(endTime-startTime)+"ms");}publicstaticvoidmain(String[] args)throws Exception {test01();test02();test03();}}