反射

作者: 在一颗大大大榕树下 | 来源:发表于2019-07-22 10:40 被阅读0次

    获取有参构造和无参构造

    基础类

    public class Rat {
    
        public Rat(){
            go();
        }
    
        public Rat(int count){
            go(count);
        }
    
        private void go(int count) {
            Log.i("Rat","hello,你走了有参构造,小白鼠一共"+count+"只");
        }
    
        private void go() {
            Log.i("Rat","hello,你走了无参构造");
        }
    }
    

    实现:

            var rat:Rat? = null
            try {
                val clazz: Class<Rat> = Class.forName("com.yirong.myapplication.Rat") as Class<Rat>
    //            rat = clazz.getDeclaredConstructor().newInstance()//获取无参构造
                rat = clazz.getDeclaredConstructor(Int::class.java).newInstance(27)//获取有参构造
    
            }catch (e: ClassNotFoundException){
                if (Log.isLoggable(TAG, Log.WARN)) {
                    Log.w(
                        TAG, "ClassNotFound"
                    )
                }
            } catch (e: InstantiationException) {
                Log.w(
                    TAG, "InstantiationException"
                )
            } catch (e: IllegalAccessException) {
                Log.w(
                    TAG, "IllegalAccessException"
                )
            } catch (e: NoSuchMethodException) {
                Log.w(
                    TAG, "NoSuchMethodException"
                )
            } catch (e: InvocationTargetException) {
                Log.w(
                    TAG, "InvocationTargetException"
                )
            }
    

    查看日志

    10:39:28.206 2207-2207/? I/Rat: hello,你走了无参构造
    10:39:28.206 2207-2207/? I/Rat: hello,你走了有参构造,小白鼠一共27只
    

    相关文章

      网友评论

          本文标题:反射

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