zoukankan      html  css  js  c++  java
  • java反射抄的例子

    package com.reflect;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.Modifier;
    
    /*
     * 反射的概念
     *     指程序可以访问,检测和修改它本身状态或者行为的一种能力,并能根据自身行为的状态和结果,调整或修改应用所描述行为的状态和相关的语义
     *     反射是java中的一种强大的工具,能够使我们很方便的创建灵活的代码,这些代码可以运行时的装配,无需在组件之间进行源代码链接
     * 
     * 反射机制的作用:
     *     1、反编译:.class-->.java
     *     2、通过反射机制访问java对象的属性,方法构造等
     * 
     * sun提供的反射机制的类:
     *     Class
     *     Constructor
     *    Field
     *     Method
     *     Modifier
     */
    public class Study01 {
        
        public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchFieldException, InstantiationException, IllegalAccessException {
            Study01 s=new Study01();
            s.test04();
        }
        public void test01() throws ClassNotFoundException{
            //获取类的三种方法:
            Class c1=Class.forName("DVD");
            
            Class c2=ClassDemo.class;
            
            ClassDemo c=new ClassDemo();
            Class c3=c.getClass();
        }
        
        public void test02() throws ClassNotFoundException, InstantiationException, IllegalAccessException{
            //创建对象,利用newInstance
            Class c=Class.forName("DVD");
            
            Object o=c.newInstance();
        }
        
        public void test03() throws ClassNotFoundException{
            //获取整个类
            Class c=Class.forName("com.entity.DVD");//注意class.forName()需要类的全名,包括包
            //获取所有所有的属性
            Field[] fs=c.getDeclaredFields();
            //定义可变长的字符串来存储属性
            StringBuilder sb=new StringBuilder();
            //通过追缴的方法,将每个属性凭借到此字符串中
            //最外边的public定义
               sb.append(Modifier.toString(c.getModifiers()) + " class " + c.getSimpleName() +"{
    "); 
               //里面的每一个属性
               for(Field field:fs){
                   sb.append("	");
                   sb.append(Modifier.toString(field.getModifiers())+" ");//获得属性的访问修饰符
                   sb.append(field.getType().getSimpleName()+" ");//属性的类型名
                   sb.append(field.getName()+";
    ");//属性的名字+回车
               }
               sb.append("}");
               System.out.println(sb);
        }
        
        public void test04() throws ClassNotFoundException, SecurityException, NoSuchFieldException, InstantiationException, IllegalAccessException{
            //获取指定属性
            Class c=Class.forName("com.entity.DVD");
            Field name=c.getDeclaredField("name");
            Object o=c.newInstance();
            name.setAccessible(true);//使用反射机制可以打破封装性,导致了java对象的属性不安全
            name.set(o, "guo");//给o对象的id赋值“guo"
            System.out.println(name.get(o));
        }
        
        public void test05(){
            /*
             * 方法关键字:
             * getDeclaredMethods() 获取所有方法
             * getReturnType() 获取返回值类型
             * getParameterTypes() 获取方法的传入参数类型
             * getDeclaredMethod("方法名",参数类型.class...) 获得特定方法
             * 
             * 构造关键字:
             * getDeclaredConstructors() 获取所有的构造方法
             * getDeclaredConstructors(参数类型.class,...)获取特定构造
             * 
             * 父类和接口
             * getSuperclass() 获取某类的父类
             * getInterfaces() 获取某类实现的接口
             * 
             * 对于java这种先编译后执行的语言来说,反射机制可以使代码更灵活,更加容易实现面向对象         */
        }
    }
    package com.reflect02;
    
    import java.lang.reflect.Array;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    
    class Study01 {
        public static void main(String[] args) {
            hello h=new hello();
            h.test15();
        }
    }
    
    
    class Demo{
        
    }
    class hello{
        /*
         * 通过一个对象获取完整的包名和类名
         */
        public void test01(){
            Demo demo=new Demo();
            System.out.println(demo.getClass().getName());
        }
        
        /*
         * 实例化class类对象
         */
        public void test02(){
            Class<?> demo1=null;
            Class<?> demo2=null;
            Class<?> demo3=null;
            try {
                demo1=Class.forName("com.reflect02.Demo");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            demo2=new Demo().getClass();
            demo3=Demo.class;
            
            System.out.println("类名称  "+demo1.getName());
            System.out.println("类名称 "+demo2.getName());
            System.out.println("类名称 "+demo3.getName());
        }
        /*
         * 通过无参构造实例化对象
         */
        public void test03(){
            Class<?> demo=null;
            try {
                demo=Class.forName("com.reflect02.Person");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            Person per=null;
            try {
                per=(Person) demo.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            per.setName("guo");
            per.setAge(12);
            System.out.println(per);
        }
        
        /*
         * 调用各种构造创建对象
         */
        public void test04(){
            Class<?> demo=null;
            try {
                demo=Class.forName("com.reflect02.Person");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            Person per1=null;
            Person per2=null;
            Person per3=null;
            Person per4=null;
            
            Constructor<?> cons[]=demo.getConstructors();
    //        System.out.println(cons[0]);可以先输出找到他们的顺序
    //        System.out.println(cons[1]);
    //        System.out.println(cons[2]);
    //        System.out.println(cons[3]);
    //        
            try {
                per2=(Person) cons[0].newInstance((Object)"guo",(Object)12);
                per3=(Person) cons[1].newInstance("liu");
                per4=(Person) cons[2].newInstance(23);
                per1=(Person) cons[3].newInstance();
                
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            System.out.println(per1);
            System.out.println(per2);
            System.out.println(per3);
            System.out.println(per4);
        }
        /*
         * 返回一个类实现的接口
         */
        public void test05(){
            Class<?> demo=null;
            try {
                demo=Class.forName("com.reflect02.Person");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            Class<?> intes[]=demo.getInterfaces();
            for(Class<?> c:intes){
                System.out.println("实现的接口:"+c.getName());
            }
        }
        /*
         * 取得其他类中的父类
         */
        public void test06(){
            Class<?> demo=null;
            try {
                demo=Class.forName("com.reflect02.Person");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            Class<?> temp=demo.getSuperclass();
            System.out.println("继承的父类为:"+temp.getName());
        }
        /*
         * 获取其他类中全部构造函数
         */
        public void test07(){
            Class<?> demo=null;
            try {
                demo=Class.forName("com.reflect02.Person");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            Constructor<?> cons[]=demo.getConstructors();
            for(Constructor<?> c:cons){
                System.out.println(demo.getName()+"的构造方法:"+c);
            }
        }
        /*
         * 获取访问权限修饰符
         */
        public void test08(){
            Class<?> demo=null;
            try {
                demo=Class.forName("com.reflect02.Person");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            Constructor<?> cons[]=demo.getConstructors();
            for(int i=0;i<cons.length;i++){
                Class<?> p[]=cons[i].getParameterTypes();
                System.out.println("构造方法:");
                int mo=cons[i].getModifiers();
                System.out.print(Modifier.toString(mo)+" ");
                System.out.print(cons[i].getName()+"(");
                for(int j=0;j<p.length;j++){
                    System.out.print(p[j].getName()+" arg"+j);
                    if(j<p.length-1){
                        System.out.print(",");
                    }
                }
                System.out.println("){}");
            }
        }
        /*
         * 获取所有方法
         */
        public void test09(){
            Class<?> demo=null;
            try {
                demo=Class.forName("com.reflect02.Person");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            Method method[]=demo.getMethods();
            for(Method m:method){
                Class<?> returnType=m.getReturnType();
                Class<?> para[]=m.getParameterTypes();
                int temp=m.getModifiers();
                System.out.print(Modifier.toString(temp)+" ");
                System.out.print(returnType.getName()+" ");
                System.out.print(m.getName()+" ");
                System.out.print("(");
                for(int i=0;i<para.length;i++){
                    System.out.print(para[i].getName()+" arg"+i);
                    if(i<para.length-1){
                        System.out.print(",");
                    }
                }
                 Class<?> exce[]=m.getExceptionTypes();
                 if(exce.length!=0){
                     System.out.println(")throws ");
                     for(int j=0;j<exce.length;j++){
                         System.out.print(exce[j].getName()+" ");
                         if(j<exce.length-1){
                             System.out.print(",");
                         }
                     }
                 }else{
                     System.out.print(")");
                 }
                 System.out.println();
            }
        }
        /*
         * 获取其他类的全部属性
         */
        public void test10(){
            Class<?> demo=null;
            try {
                demo=Class.forName("com.reflect02.Person1");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            System.out.println("=================本地属性===================");
            Field[] field=demo.getDeclaredFields();
            for(int i=0;i<field.length;i++){
                //访问权限修饰符
                int mo=field[i].getModifiers();
                String priv=Modifier.toString(mo);
                //属性数据类型
                Class<?> type=field[i].getType();
                System.out.println(priv+" "+type.getName()+" "+field[i].getName()+";");        
            }
            
    
            System.out.println("=============实现的接口或父类的属性");
            Field[] filed1=demo.getFields();
            for(int j=0;j<filed1.length;j++){
                //权限修饰符
                int mo=filed1[j].getModifiers();
                String priv=Modifier.toString(mo);
                //属性类型
                Class<?> type=filed1[j].getType();
                System.out.println(priv+" "+type.getName()+" "+filed1[j].getName()+";");
                
            }
            
        }
        /*
         * 通过反射调用其他类中的方法
         */
        public void test11(){
            Class<?> demo=null;
            try {
                demo=Class.forName("com.reflect02.Person1");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            try {
                Method method=demo.getMethod("sayChina");
                method.invoke(demo.newInstance());
                
                method=demo.getMethod("sayHello",String.class,int.class );
                method.invoke(demo.newInstance(), "guo",22);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
            
        }
        /*
         * 调用其他类的set和get方法
         */
        public void test12(){
            Class<?> demo=null;
            Object obj=null;
            try {
                demo=Class.forName("com.reflect02.Person1");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            try {
                obj=demo.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            setter(obj,"Sex","男",String.class);
            getter(obj,"Sex");
            
        }
        /*
         * 通过反射操作属性
         */
        public void test13(){
            Class<?> demo=null;
            Object obj=null;
            try {
                demo=Class.forName("com.reflect02.Person1");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            try {
                obj=demo.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            
            try {
                Field field=demo.getDeclaredField("sex");
                field.setAccessible(true);//允许操作属性
                field.set(obj, "男");
                System.out.println(field.get(obj));
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        /*
         * 通过反射取得并修改数组的信息
         */
        public void test14(){
            int[] temp={1,2,3,4,5};
            Class<?> demo=temp.getClass().getComponentType();
            System.out.println("数组类型:"+demo.getName());
            System.out.println("数组长度:"+Array.getLength(temp));
            System.out.println("数组的第一个元素:"+Array.get(temp, 0));
            Array.set(temp, 0, 100);
            System.out.println("修改之后数组第一个元素是:"+Array.get(temp, 0));
        }
        /*
         * 通过反射修改数组大小
         */
        public void test15(){
            int[] temp={1,2,3,4,5,6,7,8,9};
            int[] newTemp=(int[]) arrayInc(temp,15);
            printA(newTemp);
            System.out.println("=======================");
            String[] atr={"a","b","c"};
            String[] str1=(String[]) arrayInc(atr,8);
            printA(str1);
        }
        
        
        public Object arrayInc(Object obj,int len){//截取一定长的数组
            Class<?> arr=obj.getClass().getComponentType();
            Object newArr=Array.newInstance(arr, len);
            int co=Array.getLength(obj);
            System.out.println(obj);
            System.arraycopy(obj,0,newArr,0,co);
            return newArr;
        }
        public void printA(Object obj){//打印数组元素
            Class<?> c=obj.getClass();
            if(!c.isArray()){
                return;
            }
            System.out.println("数组的长度为:"+Array.getLength(obj));
            for(int i=0;i<Array.getLength(obj);i++){
                System.out.print(Array.get(obj, i)+" ");
            }
        }
        public void getter(Object obj,String att){
            Method method;
            try {
                method = obj.getClass().getMethod("get"+att);
                System.out.println(method.invoke(obj));
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            
        }
        public void setter(Object obj,String att,Object value,Class<?> type){
            Method method;
            try {
                method = obj.getClass().getMethod("set"+att, type);
                method.invoke(obj, value);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            
        }
        
    }
    class Person{
        private String name;
        private int age;
        public Person() {
            super();
        }
        public Person(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
        public Person(String name){
            this.name=name;
        }
        public Person(int age){
            this.age=age;
        }
        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;
        }
        
        @Override
        public String toString() {
            return "Person [name=" + name + ", age=" + age + "]";
        }
        
    }
    interface China{
        public static final String name="guo";
        public static int age=20;
        public void sayChina();
        public void sayHello(String name,int age);
    }
    class Person1 implements China{
        private String sex;
        @Override
        public void sayChina() {
            System.out.println("hello,China");
        }
    
        @Override
        public void sayHello(String name, int age) {
            System.out.println("hello,"+name+" "+age);
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        public String getSex() {
            return sex;
        }
    
        @Override
        public String toString() {
            return "Person1 [sex=" + sex + "name=" + name+ "age=" + age+"]";
        }
        
        
    }
    package com.reflect02;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class Study02 {
        public static void main(String[] args) {
            Study02 s=new Study02();
            s.test02();
        }
        /*
         * 动态代理
         */
        public void test01(){
            test t=new test();
            System.out.println("类加载器  "+t.getClass().getClassLoader().getClass().getName());
        }
        /*
         * 在java中有三种类加载器
         * Bookstrap ClassLoader此加载器采用c++编写,一般在开发中很少见
         * Extension ClassLoader用来进行拓展类的加载,一般对应的是jrelibext目录中的类
         * AppClassLoader加载classpath指定的类,是罪常用的加载器,同时也是java中的默认加载器
         */
        public void test02(){
            MyInvocationHandler demo=new MyInvocationHandler();
            Subject sub=(Subject) demo.bind(new RealSubject());
            String info=sub.say("guo", 22);
            System.out.println(info);
        }
        /*
         * 类的生命周期
         * 
         * 在一个类编译完成之后,下一步就需要开始使用类,如果使用一个类,肯定离不来JVM。在程序执行中JVM通过装载,链接,初始化这3个步骤完成。
         * 
         * 类的装载是通过类加载器完成的,加载器将.class文件的二进制文件装入JVM的方法区,并且在堆去创建描述这个类的java.lang.Class对象。用来封装数据。但是同一个类只会被类装载器装载一次
         * 
         * 链接就是把二进制数据组装为可以运行的状态
         * 
         * 链接分为校验,准备,解析这3个阶段
         * 校验一般用来确定此二进制文件是否适合当前的JVM(版本)
         * 准备就是为静态成员分配内存空间,并设置默认值
         * 解析值得是转换常量池中的代码直接作为直接引用的过程,知道所有的符号引用都可以被运行程序使用(建立完整的对应关系)
         * 完成之后,类型也就完成了初始化,初始化之后的类的对象就可以正常使用了,看到一个对象不再使用之后,将被垃圾回收。释放空间。
         * 当没有任何引用指向class对象时就会被卸载,结束类的生命周期
         */
    }
    class test{
        
    }
    interface Subject{
        public String say(String name,int age);
    }
    class RealSubject implements Subject{
    
        @Override
        public String say(String name, int age) {
            return name+" "+age;
        }
        
    }
    /*
     * 想要完成动态代理,首先需要定义一个InvocationHandler接口的子类,已完成代理的具体操作
     */
    class MyInvocationHandler implements InvocationHandler{
        private Object obj=null;
        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            Object temp=method.invoke(this.obj,args);
            return temp;
        }
        
        public Object bind(Object obj){
            this.obj=obj;
            return  Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
                    .getClass().getInterfaces(), this);
        }
        
    }
  • 相关阅读:
    asp.net core MVC 入门学习
    C# 中关于重载与重写的区别及用法
    C# 生成随机的6位字母,包含大小写
    C# CheckBoxList绑定值,设置及获取
    jquery中checkbox的全选与反选
    docker 执行 docker system prune 导致Azure Devops build镜像失败
    Navicat 连接mysql 报错: Authentication plugin caching_ sha2_password cannot be loaded
    docker build 错误 /usr/share/dotnet/sdk/2.1.801/Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3245: Could not resolve this reference
    Azure Devops: COPY failed: stat /var/lib/docker/tmp/docker-builder268095359/xxxxxxx.csproj no such file or directory
    Azure DevOps vsts-agent-linux 安装出错, Must not run with sudo
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5579703.html
Copyright © 2011-2022 走看看