美文网首页
Java反射总结

Java反射总结

作者: 一个头发茂密的程序员 | 来源:发表于2020-11-10 15:30 被阅读0次

    新建类User:

    package entity;
    
    public class User {
        private String username;
        private String sex;
        private String age;
        public User(){
    
        }
    
        public User(String age) {
            this.age = age;
        }
    
        private User(String username,String sex){
            this.username = username;
            this.sex = sex;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
        public void sysPrintUserNameSex(String username,String sex){
            System.out.println("调用公有方法sysPrintUserNameSex:username=" + username + ";sex=" + sex);
        }
        private void sysPrintUserName(String username,String age){
            System.out.println("调用私有方法sysPrintUserName:username=" + username + ";age=" + age);
        }
    
        private static void getInfo(String username){
            System.out.println("私有的一个参数的静态方法getInfo:" + username);
        }
        private static void getInfo(String username,String sex){
            System.out.println("私有的多个参数的静态方法getInfo:username=" + username + ";sex=" + sex);
        }
        public static void pubGetInfo(String username){
            System.out.println("公有的一个参数的静态方法pubGetInfo:" + username);
        }
        public static void pubGetInfo(String username,String sex){
            System.out.println("公有的多个参数的静态方法getInfo:username=" + username + ";sex=" + sex);
        }
        @Override
        public String toString() {
            return "User{" +
                    "username='" + username + '\'' +
                    ", sex='" + sex + '\'' +
                    ", age='" + age + '\'' +
                    '}';
        }
    }
    
    

    新建接口 Mapper , Mapper2

    package dao;
    
    public interface Mapper {
        void connectionJDBC();
    }
    
    
    package dao;
    
    public interface Mapper2 {
        void connectionJDBC1();
    }
    
    

    接口实现类

    package impl;
    
    import dao.Mapper;
    import dao.Mapper2;
    
    public class UserMapperImpl implements Mapper, Mapper2 {
    
        //连接数据库方法
        @Override
        public void connectionJDBC(){
            System.out.println("Mapper进行数据库操作 CURD");
        }
    
        @Override
        public void connectionJDBC1() {
            System.out.println("Mapper2进行数据库操作 CURD");
        }
    }
    
    

    Java反射方法Demo示例

    import entity.User;
    import impl.UserMapperImpl;
    
    import java.lang.reflect.*;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class ReflectDemo {
        public static void main(String[] args) {
            //获取类对象的三种方法
            //1.Class.forName("全路径(包名+类名)");
            //2.使用.class  ,需要导入类包(import)
            //3.使用getClass()获取类对象
            try {
                /**
                 *      .class 获取类对象(常用):
                 *          Class<User> clazz = User.class;
                 */
                /**
                 *      getClass() 方法获取类对象:
                 *          Class<? extends User> clazz = new User().getClass();
                 */
    
    
    
                //Class.forName方式获取类对象(常用)
                Class<?> clazz = Class.forName("entity.User");
                //********************获取/全名 /类名 /包名************************
                System.out.println("全名:" + clazz.getName() + ";包名:" + clazz.getPackage() + ";类名:" + clazz.getSimpleName());
                //********************获取所有的公共的构造方法*************************
                Constructor<?>[] constructors = clazz.getConstructors();
                List<Constructor<?>> constructors1 = Arrays.asList(constructors);
                System.out.println("所有的公共构造方法:" + constructors1);
                //********************获取所有的构造方法(公有 + 私有)*************************
                Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
                List<Constructor<?>> constructors2 = Arrays.asList(declaredConstructors);
                System.out.println("所有的构造方法(公有 + 私有):" + constructors2);
                //********************根据参数类型获取公共的构造方法*************************
                Constructor<?> constructor1 = clazz.getConstructor(String.class);
                Object o1 = constructor1.newInstance("根据参数类型获取公共的构造方法创建的实例");
    
                System.out.println(o1);
                System.out.println("根据参数类型获取公共的构造方法:" + constructor1);
                System.out.println("构造方法类型:" + Modifier.toString(constructor1.getModifiers()));
                //********************根据参数类型获取所有的构造方法*************************
                Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(String.class, String.class);
                declaredConstructor.setAccessible(true);
                Object o2 = declaredConstructor.newInstance("私有构造方法实例", "私有构造方法实例");
                System.out.println(o2);
                System.out.println("根据参数类型获取所有的构造方法(公共+私有):" + declaredConstructor);
                System.out.println("构造方法类型:" + Modifier.toString(declaredConstructor.getModifiers()));
                //*********************获取公共的无参构造方法************************
                Constructor<?> constructor = clazz.getConstructor();
                //*********************根据无参构造方法创建类实例*************************
                Object user = constructor.newInstance();
                //*********************根据方法名称和参数类型获取公共方法*********************************
                Method sysPrintUserNameSexMethod = clazz.getMethod("sysPrintUserNameSex",new Class[]{String.class,String.class});
                sysPrintUserNameSexMethod.invoke(user,"李四","男");
                System.out.println("方法类型:" + Modifier.toString(sysPrintUserNameSexMethod.getModifiers()));
                System.out.println("方法所属类:" + sysPrintUserNameSexMethod.getDeclaringClass());
                //*********************根据方法名称和参数类型获取指定的类成员方法(公共私有都可获取)**************************
                Method method = clazz.getDeclaredMethod("sysPrintUserName", new Class[]{String.class,String.class});
                //暴力访问 private方法   private方法需要设置setAccessible(true)为true的条件下才可访问
                method.setAccessible(true);
                method.invoke(user,"张三","21");
                System.out.println("方法类型:" + Modifier.toString(method.getModifiers()));
                //*****************根据方法名获取公有的静态方法****************
                Method pubGetInfo = clazz.getMethod("pubGetInfo", String.class);
                pubGetInfo.invoke(user,"王五");
                System.out.println("方法类型:" + Modifier.toString(pubGetInfo.getModifiers()));
                //*****************根据方法名获取多个参数公有的静态方法****************
                Method overWritePubGetInfo = clazz.getDeclaredMethod("pubGetInfo", new Class[]{String.class,String.class});
                overWritePubGetInfo.invoke(user,"王五","15");
                System.out.println("方法类型:" + Modifier.toString(overWritePubGetInfo.getModifiers()));
                //*****************根据方法名获取私有的静态方法****************
                Method getInfo = clazz.getDeclaredMethod("getInfo", String.class);
                getInfo.setAccessible(true);
                getInfo.invoke(user,"王五");
                //*****************根据方法名获取多个参数私有的静态方法****************
                Method overWriteGetInfo = clazz.getDeclaredMethod("getInfo", new Class[]{String.class,String.class});
                overWriteGetInfo.setAccessible(true);
                overWriteGetInfo.invoke(user,"王五","15");
                //*****************获取类的私有字段并修改值******************************
                Field field = clazz.getDeclaredField("sex");
                field.setAccessible(true);
                System.out.println("字段所属类:" + field.getDeclaringClass());
                //*********************获取的值********************************
                Object o = field.get(o2);
                System.out.println("通过反射获取username的值:" + o);
                //*********************设置sex的值********************************
                User user1 = (User) o2;
                field.set(user1,"ABC");
                System.out.println(user1.getSex());
                //***************获取类实现的接口****************************
                Class<?>[] interfaces = UserMapperImpl.class.getInterfaces();
                List<Class<?>> classes = Arrays.asList(interfaces);
                System.out.println("实现的接口:" + classes);
                //***************获取第一个实现的接口***************************
                Class<?> anInterface = UserMapperImpl.class.getInterfaces()[0];
                System.out.println("实现的第一个接口:" + anInterface);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
    
        }
    }
    
    
    

    执行结果

    "C:\Program Files\Java\jdk1.8.0_152\bin\java.exe" "-javaagent:E:\IntelliJ IDEA 2020.1.2\lib\idea_rt.jar=56672:E:\IntelliJ IDEA 2020.1.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_152\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_152\jre\lib\rt.jar;D:\JavaStudy\out\production\JavaStudy" ReflectDemo
    全名:entity.User;包名:package entity;类名:User
    所有的公共构造方法:[public entity.User(java.lang.String), public entity.User()]
    所有的构造方法(公有 + 私有):[private entity.User(java.lang.String,java.lang.String), public entity.User(java.lang.String), public entity.User()]
    User{username='null', sex='null', age='根据参数类型获取公共的构造方法创建的实例'}
    根据参数类型获取公共的构造方法:public entity.User(java.lang.String)
    构造方法类型:public
    User{username='私有构造方法实例', sex='私有构造方法实例', age='null'}
    根据参数类型获取所有的构造方法(公共+私有):private entity.User(java.lang.String,java.lang.String)
    构造方法类型:private
    调用公有方法sysPrintUserNameSex:username=李四;sex=男
    方法类型:public
    方法所属类:class entity.User
    调用私有方法sysPrintUserName:username=张三;age=21
    方法类型:private
    公有的一个参数的静态方法pubGetInfo:王五
    方法类型:public static
    公有的多个参数的静态方法getInfo:username=王五;sex=15
    方法类型:public static
    私有的一个参数的静态方法getInfo:王五
    私有的多个参数的静态方法getInfo:username=王五;sex=15
    字段所属类:class entity.User
    通过反射获取username的值:私有构造方法实例
    ABC
    实现的接口:[interface dao.Mapper, interface dao.Mapper2]
    实现的第一个接口:interface dao.Mapper
    
    Process finished with exit code 0
    

    相关文章

      网友评论

          本文标题:Java反射总结

          本文链接:https://www.haomeiwen.com/subject/nhjjbktx.html