Foreword # #

Now that we’ve covered the basics of reflection and annotations, let’s look at how they work together to get closer and closer to our ultimate goal.

# # text

Now write a Demo that implements setContentView () functionality with annotations.

First we need to define a custom annotation, which we’ll call ContentView:

package com.lzp.annotationstudy; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by li.zhipeng on 2017/3/9. ** Created by li.zhipeng on 2017/3/9. ** Created by Li.zhipeng on 2017/3/9. public @interface ContentView { int value(); }Copy the code

The ContentView annotation is used to annotate a class (TYPE) that can be reflected at runtime. If the annotation has only one attribute, value () is recommended. The value in the annotation is stored as a key-value pair, that is, the name of the attribute corresponds to its own value. By default, value is one of the keys.

With annotations defined, it is now time to implement specific functionality through reflection:

package com.lzp.annotationstudy; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Created by li.zhipeng on 2017/3/9. ** AnnotationUtils {public static void InjectObject (Object handler){// Get the Class type of the argument Class<? > handleType = handler.getClass(); ContentView ContentView = handleType.getannotation (contentView.class);if(contentView ! = null){try {// Find the Class type by reflectionsetContentView (int param) MethodsetContentViewMethod = handleType.getMethod("setContentView", int.class); / / callsetContentView (int param), the first is the object of the operation, and the second is the method argumentsetContentViewMethod.invoke(handler, contentView.value()); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }}}}Copy the code

There are detailed comments in the code, so let’s look at the code in MainActivity:

package com.lzp.annotationstudy; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; //@ContentView(value = R.layout.activity_main) @ContentView(R.layout.activity_main) public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AnnotationUtils.injectObject(this); }}Copy the code

Here we see the benefit of recommending value, because the name is value by default, so we don’t need to write “value =”, which we would have to if it were something else, like name.

Take a look at the results:

Ok!!!!!!

# # to summarize

At this point, all the basics are over. In the demo, the class methods are reflected, and the reflection properties are pretty much the same. Next, we’ll get right to the subject: customizing the awesome database framework.