你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> 自己動手打造ICO容器

自己動手打造ICO容器

編輯:IOS開發綜合

需要五個類


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

 


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() {
System.out.println("Hello World,My Name Is Interface1Impl2");
}


}


 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved