Android IOC模块,利用了Java反射和Java注解

一、整体工程图



二、BaseActivity.java

[java]  view plain copy
  1. package com.jltxgcy.framework;  
  2. import android.os.Bundle;  
  3.   
  4. public abstract class BaseActivity extends FrameActivity  
  5. {  
  6.   
  7.     private String moduleName = "";  
  8.     private String layoutName = "";//main  
  9.   
  10.     @Override  
  11.     protected void onCreate(Bundle savedInstanceState)  
  12.     {  
  13.         super.onCreate(savedInstanceState);  
  14.         initActivity();  
  15.         onAfterOnCreate(savedInstanceState);  
  16.     }  
  17.   
  18.   
  19.     private void initActivity()  
  20.     {  
  21.         getModuleName();  
  22.         getLayoutName();  
  23.         initInjector();  
  24.         loadDefautLayout();  
  25.     }  
  26.   
  27.     protected void onAfterOnCreate(Bundle savedInstanceState)  
  28.     {  
  29.           
  30.     }  
  31.   
  32.     private void initInjector()  
  33.     {  
  34.         getInjector().injectResource(this);  
  35.         getInjector().inject(this);  
  36.     }  
  37.   
  38.     private void loadDefautLayout()  
  39.     {  
  40.         try  
  41.         {  
  42.             int layoutResID = getLayoutLoader().getLayoutID(  
  43.                     layoutName);  
  44.             setContentView(layoutResID);  
  45.         } catch (Exception e)  
  46.         {  
  47.             e.printStackTrace();  
  48.         }  
  49.     }  
  50.   
  51.     @Override  
  52.     public void setContentView(int layoutResID)  
  53.     {  
  54.         super.setContentView(layoutResID);  
  55.         getInjector().injectView(this);  
  56.         onAfterSetContentView();  
  57.     }  
  58.   
  59.   
  60.     protected void onAfterSetContentView()  
  61.     {  
  62.   
  63.     }  
  64.   
  65.     public String getModuleName()  
  66.     {  
  67.         String moduleName = this.moduleName;  
  68.         if (moduleName == null || moduleName.equalsIgnoreCase(""))  
  69.         {  
  70.             moduleName = getClass().getName().substring(0,  
  71.                     getClass().getName().length() - 8);  
  72.             String arrays[] = moduleName.split("\\.");  
  73.             this.moduleName = moduleName = arrays[arrays.length - 1]  
  74.                     .toLowerCase();  
  75.         }  
  76.         return moduleName;  
  77.     }  
  78.   
  79.     public void setModuleName(String moduleName)  
  80.     {  
  81.         this.moduleName = moduleName;  
  82.     }  
  83.   
  84.     public String getLayoutName()  
  85.     {  
  86.         String layoutName = this.layoutName;  
  87.         if (layoutName == null || layoutName.equalsIgnoreCase(""))  
  88.         {  
  89.             this.layoutName = this.moduleName;  
  90.         }  
  91.         return layoutName;  
  92.     }  
  93.   
  94.     protected void setLayoutName(String layoutName)  
  95.     {  
  96.         this.layoutName = layoutName;  
  97.     }  
  98.   
  99. }  

三、FrameActivity.java

[java]  view plain copy
  1. package com.jltxgcy.framework;  
  2.   
  3.   
  4.   
  5.   
  6.   
  7. import android.app.Activity;  
  8.   
  9. import com.jltxgcy.framework.annotation.Injector;  
  10. import com.jltxgcy.framework.layoutloader.ILayoutLoader;  
  11. import com.jltxgcy.framework.layoutloader.LayoutLoader;  
  12.   
  13. public class FrameActivity extends Activity  
  14. {  
  15.       
  16.     private ILayoutLoader mLayoutLoader;  
  17.     private Injector mInjector;  
  18.   
  19.     public ILayoutLoader getLayoutLoader()  
  20.     {  
  21.         if (mLayoutLoader == null)  
  22.         {  
  23.             mLayoutLoader = LayoutLoader.getInstance(this);  
  24.         }  
  25.         return mLayoutLoader;  
  26.     }  
  27.   
  28.     public void setLayoutLoader(ILayoutLoader layoutLoader)  
  29.     {  
  30.         this.mLayoutLoader = layoutLoader;  
  31.     }  
  32.   
  33.     public Injector getInjector()  
  34.     {  
  35.         if (mInjector == null)  
  36.         {  
  37.             mInjector = Injector.getInstance();  
  38.         }  
  39.         return mInjector;  
  40.     }  
  41.   
  42.     public void setInjector(Injector injector)  
  43.     {  
  44.         this.mInjector = injector;  
  45.     }  
  46.       
  47.   
  48. }  

四、InjectObject.java

[java]  view plain copy
  1. package com.jltxgcy.framework.annotation;  
  2.   
  3. import static java.lang.annotation.RetentionPolicy.RUNTIME;  
  4.   
  5. import java.lang.annotation.ElementType;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.Target;  
  8.   
  9. @Retention(RUNTIME)  
  10. @Target(  
  11. { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })  
  12. public @interface InjectObject  
  13. {  
  14.     boolean optional() default false;  
  15. }  

五、InjectResource.java

[java]  view plain copy
  1. package com.jltxgcy.framework.annotation;  
  2.   
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. @Target(  
  9. { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })  
  10. @Retention(RetentionPolicy.RUNTIME)  
  11. public @interface InjectResource  
  12. {  
  13.     int id() default -1;  
  14. }  

六、InjectView.java

[java]  view plain copy
  1. package com.jltxgcy.framework.annotation;  
  2.   
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. @Target(ElementType.FIELD)  
  9. @Retention(RetentionPolicy.RUNTIME)  
  10. public @interface InjectView  
  11. {  
  12.   
  13.     public int id() default -1;  
  14.   
  15.     public String click() default "";  
  16.   
  17.     public String longClick() default "";  
  18.   
  19.     public String focuschange() default "";  
  20.   
  21.     public String key() default "";  
  22.   
  23.     public String Touch() default "";  
  24. }  

七、Injector.java

[java]  view plain copy
  1. package com.jltxgcy.framework.annotation;  
  2.   
  3. import java.lang.reflect.Field;  
  4.   
  5. import android.app.Activity;  
  6. import android.content.res.Resources;  
  7.   
  8. public class Injector  
  9. {  
  10.     private static Injector instance;  
  11.   
  12.     private Injector()  
  13.     {  
  14.   
  15.     }  
  16.   
  17.     public static Injector getInstance()  
  18.     {  
  19.         if (instance == null)  
  20.         {  
  21.             instance = new Injector();  
  22.         }  
  23.         return instance;  
  24.     }  
  25.   
  26.     public void inJectAll(Activity activity)  
  27.     {  
  28.         // TODO Auto-generated method stub  
  29.         Field[] fields = activity.getClass().getDeclaredFields();  
  30.         if (fields != null && fields.length > 0)  
  31.         {  
  32.             for (Field field : fields)  
  33.             {  
  34.                 if (field.isAnnotationPresent(InjectView.class))  
  35.                 {  
  36.                     injectView(activity, field);  
  37.                 } else if (field.isAnnotationPresent(InjectResource.class))  
  38.                 {  
  39.                     injectResource(activity, field);  
  40.                 } else if (field.isAnnotationPresent(InjectObject.class))  
  41.                 {  
  42.                     inject(activity, field);  
  43.                 }  
  44.             }  
  45.         }  
  46.     }  
  47.   
  48.     private void inject(Activity activity, Field field)  
  49.     {  
  50.         // TODO Auto-generated method stub  
  51.         try  
  52.         {  
  53.             field.setAccessible(true);  
  54.             field.set(activity, field.getType().newInstance());  
  55.         } catch (Exception e)  
  56.         {  
  57.             e.printStackTrace();  
  58.         }  
  59.     }  
  60.   
  61.     private void injectView(Activity activity, Field field)  
  62.     {  
  63.         // TODO Auto-generated method stub  
  64.         if (field.isAnnotationPresent(InjectView.class))  
  65.         {  
  66.             InjectView viewInject = field.getAnnotation(InjectView.class);  
  67.             int viewId = viewInject.id();  
  68.             try  
  69.             {  
  70.                 field.setAccessible(true);  
  71.                 field.set(activity, activity.findViewById(viewId));  
  72.             } catch (Exception e)  
  73.             {  
  74.                 e.printStackTrace();  
  75.             }  
  76.         }  
  77.     }  
  78.   
  79.     private void injectResource(Activity activity, Field field)  
  80.     {  
  81.         // TODO Auto-generated method stub  
  82.         if (field.isAnnotationPresent(InjectResource.class))  
  83.         {  
  84.             InjectResource resourceJect = field  
  85.                     .getAnnotation(InjectResource.class);  
  86.             int resourceID = resourceJect.id();  
  87.             try  
  88.             {  
  89.                 field.setAccessible(true);  
  90.                 Resources resources = activity.getResources();  
  91.                 String type = resources.getResourceTypeName(resourceID);  
  92.                 if (type.equalsIgnoreCase("string"))  
  93.                 {  
  94.                     field.set(activity,  
  95.                             activity.getResources().getString(resourceID));  
  96.                 } else if (type.equalsIgnoreCase("drawable"))  
  97.                 {  
  98.                     field.set(activity,  
  99.                             activity.getResources().getDrawable(resourceID));  
  100.                 } else if (type.equalsIgnoreCase("layout"))  
  101.                 {  
  102.                     field.set(activity,  
  103.                             activity.getResources().getLayout(resourceID));  
  104.                 } else if (type.equalsIgnoreCase("array"))  
  105.                 {  
  106.                     if (field.getType().equals(int[].class))  
  107.                     {  
  108.                         field.set(activity, activity.getResources()  
  109.                                 .getIntArray(resourceID));  
  110.                     } else if (field.getType().equals(String[].class))  
  111.                     {  
  112.                         field.set(activity, activity.getResources()  
  113.                                 .getStringArray(resourceID));  
  114.                     } else  
  115.                     {  
  116.                         field.set(activity, activity.getResources()  
  117.                                 .getStringArray(resourceID));  
  118.                     }  
  119.   
  120.                 } else if (type.equalsIgnoreCase("color"))  
  121.                 {  
  122.                     if (field.getType().equals(Integer.TYPE))  
  123.                     {  
  124.                         field.set(activity,  
  125.                                 activity.getResources().getColor(resourceID));  
  126.                     } else  
  127.                     {  
  128.                         field.set(activity, activity.getResources()  
  129.                                 .getColorStateList(resourceID));  
  130.                     }  
  131.   
  132.                 }  
  133.             } catch (Exception e)  
  134.             {  
  135.                 e.printStackTrace();  
  136.             }  
  137.         }  
  138.     }  
  139.   
  140.     public void inject(Activity activity)  
  141.     {  
  142.         // TODO Auto-generated method stub  
  143.         Field[] fields = activity.getClass().getDeclaredFields();  
  144.         if (fields != null && fields.length > 0)  
  145.         {  
  146.             for (Field field : fields)  
  147.             {  
  148.                 if (field.isAnnotationPresent(InjectObject.class))  
  149.                 {  
  150.                     inject(activity, field);  
  151.                 }  
  152.             }  
  153.         }  
  154.     }  
  155.   
  156.     public void injectView(Activity activity)  
  157.     {  
  158.         // TODO Auto-generated method stub  
  159.         Field[] fields = activity.getClass().getDeclaredFields();  
  160.         if (fields != null && fields.length > 0)  
  161.         {  
  162.             for (Field field : fields)  
  163.             {  
  164.                 if (field.isAnnotationPresent(InjectView.class))  
  165.                 {  
  166.                     injectView(activity, field);  
  167.                 }  
  168.             }  
  169.         }  
  170.     }  
  171.   
  172.     public void injectResource(Activity activity)  
  173.     {  
  174.         // TODO Auto-generated method stub  
  175.         Field[] fields = activity.getClass().getDeclaredFields();  
  176.         if (fields != null && fields.length > 0)  
  177.         {  
  178.             for (Field field : fields)  
  179.             {  
  180.                 if (field.isAnnotationPresent(InjectResource.class))  
  181.                 {  
  182.                     injectResource(activity, field);  
  183.                 }  
  184.             }  
  185.         }  
  186.     }  
  187.   
  188. }  

八、ILayoutLoader.java

[java]  view plain copy
  1. package com.jltxgcy.framework.layoutloader;  
  2.   
  3. import android.content.pm.PackageManager.NameNotFoundException;  
  4.   
  5. public interface ILayoutLoader  
  6. {  
  7.     public int getLayoutID(String resIDName) throws ClassNotFoundException,  
  8.             IllegalArgumentException, IllegalAccessException,  
  9.             NameNotFoundException;  
  10.   
  11. }  

九、LayoutLoader.java

[java]  view plain copy
  1. package com.jltxgcy.framework.layoutloader;  
  2.   
  3. import java.lang.reflect.Field;  
  4.   
  5. import android.content.Context;  
  6. import android.content.pm.PackageInfo;  
  7. import android.content.pm.PackageManager;  
  8. import android.content.pm.PackageManager.NameNotFoundException;  
  9. import android.util.Log;  
  10.   
  11. public class LayoutLoader implements ILayoutLoader  
  12. {  
  13.   
  14.     private static LayoutLoader instance;  
  15.     private Context mContext;  
  16.   
  17.     private LayoutLoader(Context context)  
  18.     {  
  19.         this.mContext = context;  
  20.     }  
  21.   
  22.     public static LayoutLoader getInstance(Context context)  
  23.     {  
  24.         if (instance == null)  
  25.         {  
  26.             instance = new LayoutLoader(context);  
  27.         }  
  28.         return instance;  
  29.     }  
  30.   
  31.     public int getLayoutID(String resIDName) throws NameNotFoundException,  
  32.             ClassNotFoundException, IllegalArgumentException,  
  33.             IllegalAccessException  
  34.     {  
  35.         int resID = readResID("layout", resIDName);  
  36.         if (resID == 0)  
  37.         {  
  38.               
  39.         }  
  40.         return resID;  
  41.     }  
  42.   
  43.     public int readResID(String type, String resIDName)  
  44.             throws NameNotFoundException, ClassNotFoundException,  
  45.             IllegalArgumentException, IllegalAccessException  
  46.     {  
  47.         String packageName;  
  48.         PackageManager pm = mContext.getPackageManager();  
  49.         PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), 0);  
  50.         packageName = pi.packageName;  
  51.         if (packageName == null || packageName.equalsIgnoreCase(""))  
  52.         {  
  53.             throw new NameNotFoundException("没有发现类");  
  54.         }  
  55.         packageName = packageName + ".R";  
  56.         Class<?> clazz = Class.forName(packageName);  
  57.         Class<?> cls = readResClass(clazz, packageName + "$" + type);  
  58.         if (cls == null)  
  59.         {  
  60.             throw new NameNotFoundException("没有发现类");  
  61.         }  
  62.         return readResID(cls, resIDName);  
  63.   
  64.     }  
  65.   
  66.     public Class<?> readResClass(Class<?> cls, String respackageName)  
  67.     {  
  68.         Class<?>[] classes = cls.getDeclaredClasses();  
  69.         for (int i = 0; i < classes.length; i++)  
  70.         {  
  71.             Class<?> tempClass = classes[i];  
  72.             Log.v("TAReadSystemRes", tempClass.getName());  
  73.             if (tempClass.getName().equalsIgnoreCase(respackageName))  
  74.             {  
  75.                 return tempClass;  
  76.             }  
  77.         }  
  78.         return null;  
  79.     }  
  80.   
  81.     public int readResID(Class<?> cls, String resIDName)  
  82.             throws IllegalArgumentException, IllegalAccessException  
  83.     {  
  84.   
  85.         Field[] fields = cls.getDeclaredFields();  
  86.         for (int j = 0; j < fields.length; j++)  
  87.         {  
  88.             if (fields[j].getName().equalsIgnoreCase(resIDName))  
  89.             {  
  90.                 return fields[j].getInt(cls);  
  91.             }  
  92.         }  
  93.         return 0;  
  94.     }  
  95.   
  96. }  

十、MainActivity.java

[java]  view plain copy
  1. package com.jltxgcy.iocdemo;  
  2.   
  3. import android.os.Bundle;  
  4. import android.view.View;  
  5. import android.view.View.OnClickListener;  
  6. import android.widget.Button;  
  7. import android.widget.TextView;  
  8.   
  9. import com.jltxgcy.framework.BaseActivity;  
  10. import com.jltxgcy.framework.annotation.InjectResource;  
  11. import com.jltxgcy.framework.annotation.InjectView;  
  12.   
  13. public class MainActivity extends BaseActivity {  
  14.     @InjectResource(id=R.string.app_name)  
  15.     String appNameString;  
  16.     @InjectView(id=R.id.tv_display)  
  17.     TextView tView;  
  18.     @InjectView(id=R.id.btn_imagecache)  
  19.     Button btnImagecache;  
  20.     @InjectView(id=R.id.btn_http)  
  21.     Button btnHttp;  
  22.   
  23.     @Override  
  24.     protected void onAfterOnCreate(Bundle savedInstanceState)  
  25.     {  
  26.         tView.setText(appNameString);  
  27.         super.onAfterOnCreate(savedInstanceState);  
  28.           
  29.     }  
  30.       
  31.     @Override  
  32.     protected void onAfterSetContentView()  
  33.     {  
  34.         // TODO Auto-generated method stub  
  35.         super.onAfterSetContentView();  
  36.         OnClickListener onClickListener = new OnClickListener()  
  37.         {  
  38.   
  39.             @Override  
  40.             public void onClick(View v)  
  41.             {  
  42.                 // TODO Auto-generated method stub  
  43.                 switch (v.getId())  
  44.                 {  
  45.                 case R.id.btn_imagecache:  
  46.                     tView.setText("图片缓存模块");  
  47.                     break;  
  48.                 case R.id.btn_http:  
  49.                     tView.setText("http模块");  
  50.                     break;  
  51.                 default:  
  52.                     break;  
  53.                 }  
  54.             }  
  55.         };  
  56.         btnImagecache.setOnClickListener(onClickListener);  
  57.         btnHttp.setOnClickListener(onClickListener);  
  58.     }  
  59.   
  60. }  

十一、main.xml

[java]  view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical"  
  6.     tools:context=".MainActivity" >  
  7.    
  8.     <TextView  
  9.         android:id="@+id/tv_display"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:text="@string/hello_world" />  
  13.        <Button  
  14.         android:id="@+id/btn_imagecache"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="图片缓存模块" />  
  18.        <Button  
  19.         android:id="@+id/btn_http"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:text="HTTP模块" />  
  23.   
  24. </LinearLayout>  

十二、解释

           field.isAnnotationPresent(InjectView.class),判断该字段上是否有注解。如果有可以取得注解的内容。注解是动态解析的。

           @Override 

           @Deprecated 

           @SuppressWarnings 这些都是注解

            1、定义注解

[java]  view plain copy
  1. package com.jltxgcy.framework.annotation;  
  2.   
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. @Target(  
  9. { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })  
  10. @Retention(RetentionPolicy.RUNTIME)  
  11. public @interface InjectResource  
  12. {  
  13.     int id() default -1;  
  14. }  

            2、使用注解(@的方式)

[java]  view plain copy
  1. @InjectResource(id=R.string.app_name)  
  2.     String appNameString;  
           3、在程序中动态注入。Inject。

[java]  view plain copy
  1. private void injectResource(Activity activity, Field field)  
  2.     {  
  3.         // TODO Auto-generated method stub  
  4.         if (field.isAnnotationPresent(InjectResource.class))  
  5.         {  
  6.             InjectResource resourceJect = field  
  7.                     .getAnnotation(InjectResource.class);  
  8.             int resourceID = resourceJect.id();  
  9.             try  
  10.             {  
  11.                 field.setAccessible(true);  
  12.                 Resources resources = activity.getResources();  
  13.                 String type = resources.getResourceTypeName(resourceID);  
  14.                 if (type.equalsIgnoreCase("string"))  
  15.                 {  
  16.                     field.set(activity,  
  17.                             activity.getResources().getString(resourceID));  
  18.                 } else if (type.equalsIgnoreCase("drawable"))  
  19.                 {  
  20.                     field.set(activity,  
  21.                             activity.getResources().getDrawable(resourceID));  
  22.                 } else if (type.equalsIgnoreCase("layout"))  
  23.                 {  
  24.                     field.set(activity,  
  25.                             activity.getResources().getLayout(resourceID));  
  26.                 } else if (type.equalsIgnoreCase("array"))  
  27.                 {  
  28.                     if (field.getType().equals(int[].class))  
  29.                     {  
  30.                         field.set(activity, activity.getResources()  
  31.                                 .getIntArray(resourceID));  
  32.                     } else if (field.getType().equals(String[].class))  
  33.                     {  
  34.                         field.set(activity, activity.getResources()  
  35.                                 .getStringArray(resourceID));  
  36.                     } else  
  37.                     {  
  38.                         field.set(activity, activity.getResources()  
  39.                                 .getStringArray(resourceID));  
  40.                     }  
  41.   
  42.                 } else if (type.equalsIgnoreCase("color"))  
  43.                 {  
  44.                     if (field.getType().equals(Integer.TYPE))  
  45.                     {  
  46.                         field.set(activity,  
  47.                                 activity.getResources().getColor(resourceID));  
  48.                     } else  
  49.                     {  
  50.                         field.set(activity, activity.getResources()  
  51.                                 .getColorStateList(resourceID));  
  52.                     }  
  53.   
  54.                 }  
  55.             } catch (Exception e)  
  56.             {  
  57.                 e.printStackTrace();  
  58.             }  
  59.         }  
  60.     }  

            代码地址:https://github.com/jltxgcy/Demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值