Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1538367
  • 博文数量: 237
  • 博客积分: 5139
  • 博客等级: 大校
  • 技术积分: 2751
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-18 14:48
文章分类

全部博文(237)

文章存档

2016年(1)

2012年(4)

2011年(120)

2010年(36)

2009年(64)

2008年(12)

分类: Java

2012-04-16 16:48:32

PackageManager pm = getPackageManager();
Intent i = new Intent(Constants.ACTION_RUNNABLE_SERVICE);        // 自己定义的action
List list = pm.queryIntentServices(i, PackageManager.GET_RESOLVED_FILTER);
mServiceList = new ArrayList();
for (ResolveInfo ri: list) {
try {
       //forName: Returns a Class object which represents the class with the specified name
 //asSubClass:Casts this Class to represent a subclass of the specified class. 
                               //If successful, this Class is returned; otherwise a ClassCastException is thrown.
Class svcClass = Class.forName(ri.serviceInfo.name)
.asSubclass(Service.class);
                               
                                // 获取参数的类型, 这里将参数类型设置为Service
Class[] paramType = new Class[] {Service.class};
                               //Returns a Constructor object which represents the public constructor matching
                                // the specified parameter types.
                                Constructor ctor = svcClass.getConstructor(paramType);
                                
                                
Object[] obj = new Object[] {this};
Service svc = (Service)ctor.newInstance(obj);
Log.v(TAG, "Add " + ri.serviceInfo.name);
mServiceList.add(new RunnableService(svc, ri.filter));
} catch (Exception e) {
Log.e(TAG, "Fail to create service.", e);
}
}

----运行时生成instance
     想生成对象的实体,在反射动态机制中有两种方法,一个针对无变量的构造方法,一个针对带参数的
构造方法,,如果想调用带参数的构造方法,就比较的麻烦,不能直接调用Class类中的newInstance()
,而是调用Constructor类中newInstance()方法,首先准备一个Class[]作为Constructor的参数类型。
然后调用该Class对象的getConstructor()方法获得一个专属的Constructor的对象,最后再准备一个
Object[]作为Constructor对象的newInstance()方法的实参。
      在这里需要说明的是 只有两个类拥有newInstance()方法,分别是Class类和Constructor类
Class类中的newInstance()方法是不带参数的,而Constructro类中的newInstance()方法是带参数的
需要提供必要的参数。
阅读(2949) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~