I get the impression that 开发者_JAVA技巧Android supports reflection. But does it really? How sensible would it be to rely on reflection heavily? What's the penalty?
It is supported, and even recommended in the situation where you want compatibility with multiple versions of the Android OS in one apk
file. This article from the official Android Developers Blog describes how to build an app that requires only some early version of the API, and uses reflection to invoke new APIs if they are available:
Backward compatibility for Android applications
Android supports reflection.
Once you've got a prototype running, you can benchmark and determine your bottlenecks.
If its reflection, then consider trying to cache interfaces and such to make it a one-off cost, rather than continually resolving the same interfaces from the same instances repeatedly.
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);
There is a nice example of reflection in the sample code as well, in BusinessCard. This method wont result in a bunch of expections being thrown, so it should be much more performance friendly. It is also, in my opinion, easier to implement. Especially if it concerns a previously unimplemented method.
Here is where it is used: http://developer.android.com/resources/samples/BusinessCard/src/com/example/android/businesscard/ContactAccessor.html
Android of course supports Reflection and we can read methods of a different APK or Framework class. Here is an article on using Reflection in Android as a possible design approach to create API- http://prasanta-paul.blogspot.kr/2013/09/java-reflection-as-android-api.html
精彩评论