Reflection Java 反射(九)

来源:互联网 发布:新东方 知乎 编辑:程序博客网 时间:2024/05/22 01:49
import java.lang.reflect.Method;

/**
 * 通过反射技术,获得类对象   方法属性
 * 放射获得了自由,提高了效率,丢了些性能
 * 10亿次调用同一方法耗时:毫秒数
 * 通过反射,耗时毫秒数:1682
         通过反射,关闭安全检测,耗时毫秒数:962
         常规,对象.方法,耗时毫秒数:24
 */
public class ReflectDemo3 {
public static void main(String[] args) throws Exception {
test01();
test02();
test03();
}
/**
* 反射 方式
* @throws Exception
*/
public static void test01() throws Exception{
String path="mine.annotation.StudentDemo";
//通过:包名+类名     获得类对象
Class<?> cla= Class.forName(path);
StudentDemo st=(StudentDemo)cla.newInstance();
//通过反射技术 调用方法
Method method=cla.getDeclaredMethod("setId",int.class);
long start=System.currentTimeMillis();
for(int i=0;i<1000000000;i++){
method.invoke(st, 100);
}
long timeSum=System.currentTimeMillis()-start;
System.out.println("通过反射,耗时毫秒数:"+timeSum);
}
/**
* 反射+关闭安全检查 方式
* @throws Exception
*/
public static void test02() throws Exception{
String path="mine.annotation.StudentDemo";
//通过:包名+类名     获得类对象
Class<?> cla= Class.forName(path);
StudentDemo st=(StudentDemo)cla.newInstance();
//通过反射技术 调用方法
Method method=cla.getDeclaredMethod("setId",int.class);
method.setAccessible(true);//关闭安全检测
long start=System.currentTimeMillis();
for(int i=0;i<1000000000;i++){
method.invoke(st, 100);
}
long timeSum=System.currentTimeMillis()-start;
System.out.println("通过反射,关闭安全检测,耗时毫秒数:"+timeSum);
}
/**
* 常规    方式

*/
public static void test03(){
StudentDemo st=new StudentDemo();
long start=System.currentTimeMillis();
for(int i=0;i<1000000000;i++){
st.setId(100);
}
long timeSum=System.currentTimeMillis()-start;
System.out.println("常规,对象.方法,耗时毫秒数:"+timeSum);
}

}

//==============分割线===下面只是测试类=== 随便写================

/**
 * 假定要与数据库中  表:td_student对应
 * @author Administrator
 *
 */
@Table (value="st_student")
public class StudentDemo {
@Fields(columnName="id",type="int",length=10)//对ID经行注解
private int id;
@Fields(columnName="name",type="varchar",length=10)
private String name;
@Fields(columnName="age",type="int",length=3)
private int age;

public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public int getAge() {
return age;
}


public void setAge(int age) {
this.age = age;
}


@MyAnno(name="")
public void test(){}

@MyAnno2("lisi")//一个值,直接赋值"lisi",也可以,value=“lisi”
public void test(int str){
System.out.println(str);
}

}

0 0
原创粉丝点击