自己動手打造ICO容器

來源:互聯網
上載者:User

需要五個類


(容器類),需要用此容器管理的類全部整合此類

 


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");
}


}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.