package 反射;//测试性能分析
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main2 {
//普通方式调用
public static void test01(){
User user1=new User();
//第一:创建两个时间,来查看程序运行了多久
long stsyemTime=System.currentTimeMillis();//开始时间
for (int i=0;i<1000000000 ;i++ ){
user1.getName();//不断获取他的名字
}
long endmTime=System.currentTimeMillis();//开始时间
//查看用时
System.out.println("普通方法获取10亿次用时"+(endmTime-stsyemTime)+"ms");
}
//反射方式调用
//普通方式调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user=new User();
//通过clss方式获取对象
Class c1=user.getClass();
//获取指定名称的方法
Method getName=c1.getDeclaredMethod("getName",null);
//第一:创建两个时间,来查看程序运行了多久
long stsyemTime=System.currentTimeMillis();//开始时间
for (int i=0;i<1000000000 ;i++ ){
getName.invoke(user,null);
}
long endmTime=System.currentTimeMillis();//开始时间
//查看用时
System.out.println("反射方获取10亿次用时"+(endmTime-stsyemTime)+"ms");
}
//关闭安全检查调用
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User3 user=new User3();
//通过clss方式获取对象
Class c1=user.getClass();
//获取指定名称的方法
Method getName=c1.getDeclaredMethod("getName",null);
//关闭权限检查
getName.setAccessible(true);
//第一:创建两个时间,来查看程序运行了多久
long stsyemTime=System.currentTimeMillis();//开始时间
for (int i=0;i<1000000000 ;i++ ){
getName.invoke(user,null);
}
long endmTime=System.currentTimeMillis();//开始时间
//查看用时
System.out.println("关闭检测方法获取10亿次用时"+(endmTime-stsyemTime)+"ms");
}
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
test01();
test02();
test03();
}
}
//实体类:pojo,entity:来表示实体类
class User3{
private String name;
private int id;
private int age;
public User3(){
}
public User3(String name,int id,int age){
this.name=name;
this.id=id;
this.age=age;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
//------------------
public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}
//--------------
public void setAge(int age){
this.age=age;
}
public int getAge(){
return age;
}
//输出方法
public String toString(){
return "User{"+"name="+name+"id="+id+"age="+age+"}";
}
}