码迷,mamicode.com
首页 > 编程语言 > 详细

Java反射的基本应用

时间:2017-05-31 12:12:28      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:generic   res   java反射   interface   构造方法   trace   print   加载   tcl   

反射机制,程序在运行时加载新的类,使程序更加灵活

public class HelooReflect {
    public static void main(String[] args) {
        // 获取类
        testClass();
    }
    private static void testClass() {
        // 创建一个学生类的对象
        Student student = new Student();
        try {
            // 开始获取类
            Class clazz1 = Student.class;
            Class clazz2 = student.getClass();
            Class clazz3 = Class.forName("com.bjsxt.java.clc.fanshe.Student");
            //判断类对象是否相等
            System.out.println(clazz1 == clazz2);
            System.out.println(clazz1 == clazz3);
            //常见 方法
            System.out.println("类的名字" + clazz1.getName());
            System.out.println("类的简称" + clazz1.getSimpleName());
            System.out.println("包的信息" + clazz1.getPackage().getName());
            System.out.println("获取包名" + clazz1.getPackage());
            System.out.println("获取修饰符" + clazz1.getModifiers());
            System.out.println("获取父类" + clazz1.getSuperclass());
            System.out.println("获取父类的超类" + clazz1.getGenericSuperclass());
            System.out.println("判断是否为接口" + clazz1.isInterface());
            System.out.println("获取类加载器" + clazz1.getClassLoader());
            
            //基本类型9=(8种基本数据类型的类+1void)
            System.out.println(int.class == Integer.class);//不等
            //判断是否是基本类型
            System.out.println(int.class.isPrimitive());
            System.out.println(Integer.class.isPrimitive());
            System.out.println("数组是引用类型" + int[].class.isPrimitive());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 获取类的名字,方法,属性,构造器

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test2 {
    public static void main(String[] args) {
        try {
            Class clazz = Class.forName("bean.User");
            // 获取类的名字
            clazz.getName();
            /**
             * 获取属性信息
             */
            // 只能获取public的属性
            Field[] fields1 = clazz.getFields();
            // 可以获得所有的属性
            Field[] fields2 = clazz.getDeclaredFields();
            // 输出获取到的属性的个数
            System.out.println(fields1.length);
            System.out.println(fields2.length);
            // 遍历获取到的属性
            for (Field field : fields2) {
                System.out.println("属性" + field);
            }
            // 获得属性的权限
            Field f = clazz.getDeclaredField("uname");
            System.out.println(f);
            /**
             * 获取方法的信息
             */
            Method[] methods = clazz.getDeclaredMethods();
            Method m01 = clazz.getDeclaredMethod("getUname", null);
            // 如果方法有参,则必须传递参数类型对应的class对象
            Method m02 = clazz.getDeclaredMethod("setUname", String.class);
            for (Method method : methods) {
                System.out.println("方法" + method);
            }
            /**
             *获取构造器信息 
             */
            Constructor[] constructors = clazz.getDeclaredConstructors();
            Constructor c = clazz.getDeclaredConstructor(int.class,int.class,String.class);
            System.out.println("获得构造器"+c);
            for (Constructor constructor : constructors) {
                System.out.println("构造器"+constructor);
            }
            
            
            
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 通过反射操作类的属性,方法构造器

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import bean.User;
/**
 * @author clc
 *
 */
public class Test3 {
    public static void main(String[] args) {
        try {
            Class<User> clazz = (Class<User>) Class.forName("bean.User");
            // 通过反射API调用构造方法,构造对象
            // 其实调用了User的无参构造方法
            User u1 = clazz.newInstance();
            System.out.println(u1);
            // 有参调用构造器
            Constructor<User> c = clazz.getDeclaredConstructor(int.class, int.class, String.class);
            User u2 = c.newInstance(1234, 22, "clc");
            System.out.println(u2);
            // 通过反射调用普通方法
            User u3 = clazz.newInstance();
            Method method = clazz.getDeclaredMethod("setUname", String.class);
            // 相当于u3.setUname("clc3");
            method.invoke(u3, "clc3");
            System.out.println(u3);
            // 通过反射操作属性
            User u4 = clazz.newInstance();
            Field f = clazz.getDeclaredField("uname");
            // 设置属性不需要安全检查,可以直接访问
            f.setAccessible(true);
            // 通过反射直接设置属性
            f.set(u4, "clc4");
            // 通过反射直接读取属性值
            System.out.println(u4.getUname());
            System.out.println(f.get(u4));
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

辅助类User

package bean;
public class User {
    private int id;
    private int age;
    private String uname;
    @Override
    public String toString() {
        return "User [id=" + id + ", age=" + age + ", uname=" + uname + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + id;
        result = prime * result + ((uname == null) ? 0 : uname.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (age != other.age)
            return false;
        if (id != other.id)
            return false;
        if (uname == null) {
            if (other.uname != null)
                return false;
        } else if (!uname.equals(other.uname))
            return false;
        return true;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public User(int id, int age, String uname) {
        super();
        this.id = id;
        this.age = age;
        this.uname = uname;
    }
    public User() {
        super();
    }
}

 

 

 

 

 

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
import bean.User;
 
/**
 * @author clc
 *
 */
public class Test3 {
    public static void main(String[] args) {
        try {
            Class<User> clazz = (Class<User>Class.forName("bean.User");
            // API,
 
            // User
            User u1 = clazz.newInstance();
            System.out.println(u1);
 
            // 
            Constructor<User> c = clazz.getDeclaredConstructor(int.classint.classString.class);
            User u2 = c.newInstance(123422"clc");
            System.out.println(u2);
 
            // 
            User u3 = clazz.newInstance();
            Method method = clazz.getDeclaredMethod("setUname"String.class);
 
            // u3.setUname("clc3");
            method.invoke(u3"clc3");
            System.out.println(u3);
 
            // 
            User u4 = clazz.newInstance();
            Field f = clazz.getDeclaredField("uname");
            // ,访
            f.setAccessible(true);
            // 
            f.set(u4"clc4");
            // 
            System.out.println(u4.getUname());
            System.out.println(f.get(u4));
 
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

Java反射的基本应用

标签:generic   res   java反射   interface   构造方法   trace   print   加载   tcl   

原文地址:http://www.cnblogs.com/chenglc/p/6923106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!