自己动手打造ICO容器

来源:未知 责任编辑:责任编辑 发表时间:2014-01-06 18:19 点击:

需要五个类


(容器类),需要用此容器管理的类全部集成此类

 


package com.metarnet.extend;


import java.lang.reflect.Field;
import com.metarnet.Injects.Inject;


/**
 * 容器
 */
public class IOC {
/**
 * 初始化
 * @param <T>
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
public void Init() throws Exception
{
Field[] fields = getClass().getDeclaredFields();
for(Field field : fields){
Inject inject=field.getAnnotation(Inject.class);
if(inject!=null)
{
field.setAccessible(true);
field.set(this,Class.forName(inject.ClassName().trim()).newInstance());
}
}
}
}
 

(注解类)

/**
 *
 */
package com.metarnet.Injects;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


/**
 * 类的依赖注入
 * @author yanfan
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
public String ClassName();
}

(主函数用于测试)

package com.metarnet.Main;


import com.metarnet.Injects.Inject;
import com.metarnet.Interfaces.Interface1;
import com.metarnet.extend.IOC;


public class TestIOC extends IOC{
@Inject(ClassName = "com.metarnet.Interfaces.imps.Interface1Impl")
private Interface1 interface1;
@Inject(ClassName = "com.metarnet.Interfaces.imps.Interface1Impl2")
private Interface1 interface2;
public Interface1 getInterface1() {
return interface1;
}


public void setInterface1(Interface1 interface1) {
this.interface1 = interface1;
}


public static void main(String[] args) {
TestIOC ioc = new TestIOC();
try {
ioc.Init();
} catch (Exception e) {
e.printStackTrace();
}
ioc.interface1.SayHello();
ioc.interface2.SayHello();
}


}

接口

package com.metarnet.Interfaces;


public interface Interface1{
public void SayHello();
}
继承接口类1

package com.metarnet.Interfaces.imps;


import com.metarnet.Interfaces.Interface1;


public class Interface1Impl implements Interface1{


@Override
public void SayHello() {
System.out.println("Hello World,My Name Is Interface1Impl");
}


}
 继承接口类2

package com.metarnet.Interfaces.imps;


import com.metarnet.Interfaces.Interface1;


public class Interface1Impl2 implements Interface1{


@Override
public void SayHello() {

发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • Lexical or Preprocessor Issue 'xxx.h
  • ios学习笔记(二)xcode 4.3.2下实现基本交互
  • ios版本的helloworld
  • iphone(object-c) 内存管理(3) 有效的内存管理 前半部分
  • ios学习笔记(一)xcode 4.3.2下创建第一个ios项目
  • IOS类似iphone通讯录TableView的完整demo【附源码】
  • UITableView一些方法
  • [iPhone中级]iPhone团购信息客户端的开发 (二)
  • 如何为Iphone应用创建启动界面
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1