Android and reflection

前端 未结 5 949
臣服心动
臣服心动 2020-12-13 13:48

I get the impression that Android supports reflection. But does it really? How sensible would it be to rely on reflection heavily? What\'s the penalty?

5条回答
  •  温柔的废话
    2020-12-13 14:08

    a simple example related to using reflection on android http://aaarkonusurum.blogspot.com/2012/02/android-ile-reflection.html

    Class x = Object.class;
    Constructor[] constructors = x.getDeclaredConstructors();
    Field[] fields = x.getDeclaredFields();
    Method[] methods = x.getDeclaredMethods();
    for (Constructor constructor : constructors) { 
        //constructors
    }
    for (Field field : fields) {
        //fields
    }
    for (Method method : methods) {
        //methods
    }    
    



    Creating a TextView from codebehind at runtime with using reflection

    String x = TextView.class.toString().replace("class ", "");
    Class cls = Class.forName(x);
    Class param[] = new Class[1];
    param[0] = Context.class; //Context=o an ki context ==> [activity.class]
    Constructor ct = cls.getConstructor(param);
    Object paramVal[] = new Object[1];
    paramVal[0] = context;
    Object retobj = ct.newInstance(paramVal); 
    



    Reaching to setText() method at the runtime

    Class methodParam[] = new Class[1];
    methodParam[0] = java.lang.CharSequence.class;
    Method method = cls.getMethod("setText", methodParam);
    Object arglist[] = new Object[1];
    arglist[0] = new String("THIS TEXTVIEW HAS BEEN CREATED ON RUN TIME");
    method.invoke(retobj, arglist); 
    

提交回复
热议问题