当前位置:编程学习 > wap >>

自己动手打造ICO容器

需要五个类


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

 


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 @inte易做图ce Inject {
public String ClassName();
}

(主函数用于测试)

package com.metarnet.Main;


import com.metarnet.Injects.Inject;
import com.metarnet.Inte易做图ces.Inte易做图ce1;
import com.metarnet.extend.IOC;


public class TestIOC extends IOC{
@Inject(ClassName = "com.metarnet.Inte易做图ces.imps.Inte易做图ce1Impl")
private Inte易做图ce1 inte易做图ce1;
@Inject(ClassName = "com.metarnet.Inte易做图ces.imps.Inte易做图ce1Impl2")
private Inte易做图ce1 inte易做图ce2;
public Inte易做图ce1 getInte易做图ce1() {
return inte易做图ce1;
}


public void setInte易做图ce1(Inte易做图ce1 inte易做图ce1) {
this.inte易做图ce1 = inte易做图ce1;
}


public static void main(String[] args) {
TestIOC ioc = new TestIOC();
try {
ioc.Init();
} catch (Exception e) {
e.printStackTrace();
}
ioc.inte易做图ce1.SayHello();
ioc.inte易做图ce2.SayHello();
}


}

接口

package com.metarnet.Inte易做图ces;


public inte易做图ce Inte易做图ce1{
public void SayHello();
}
继承接口类1

package com.metarnet.Inte易做图ces.imps;


import com.metarnet.Inte易做图ces.Inte易做图ce1;


public class Inte易做图ce1Impl implements Inte易做图ce1{


@Override
public void SayHello() {
System.out.println("Hello World,My Name Is Inte易做图ce1Impl");
}


}
 继承接口类2

package com.metarnet.Inte易做图ces.imps;


import com.metarnet.Inte易做图ces.Inte易做图ce1;


public class Inte易做图ce1Impl2 implements Inte易做图ce1{


@Override
public void SayHello() {
System.out.println("Hello World,My Name Is Inte易做图ce1Impl2");
}


}


 

补充:移动开发 , IOS ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,