Samstag, 15. Dezember 2007

Instantiating Generic Type Parameters with Factory Pattern

Some weeks ago a cowoker of mine asked me for help. He wanted to write a class with generic parameter type and create a new object of this generic type inside the class. I.E. he wanted to write something like this in Java:


public class WrongSyntax<T> {
public void someMethod() {
T object = new T(); //this line does not compile
}
}
There are some reasons why this code can't compile. Most evident reason is that T could be an interface and you can't instantiate an interface. And you have to be aware generics are boiling down to one rule : Generics are a double-check on compile time but at runtime the type parameter will be replaced by java.lang.Object and casts to the parameter type. This effect is called type erasure.

If you use java.lang.String as parameter type (and the compiler would not reject the marked line) this class would be replaced by:

public class WrongSyntax<T> {
public void someMethod() {
String object = (String) new Object();
}
}

You would get a ClassCastExcetion on runtime, therefore the compiler does not allow it.

Some days ago I read an article by Angelika Langer & Klaus Kreft regarding this problem in the German Java SPEKTRUM magazin. I'm afraid you won't find it online but there is an excellent english FAQ about Java Generics on Langer's site.

In this said article they discuss the problem of array and simple type instantiation for type parameters. Even though they brought up several solutions for arrays they came up with only one for simple types: Using reflection.


public class UsingReflection<T> {

public static <T> void createInstance(Class<T> clazz) {
T instance;
try {
instance = clazz.newInstance(); // does not work for every class
} catch (InstantiationException e) {
//...
} catch (IllegalAccessException e) {
//...
}

//...

}
}


While this will work for some classes it is obvious that it will not work for interfaces, abstract classes and classes without a default constructor.

Here are two examples that will pass the compiler but fail on runtime:



// throws java.lang.InstantiationException
new UsingReflection().createInstance(Serializable.class);

// throws java.lang.IllegalAccessException
new UsingReflection().createInstance(AbstractCollection.class);



To my mind there is a reason why instantiating type parameters is so difficult. In the first place generics are a double-check for programmers to avoid class cast exceptions. But there is more to it. Using generics brings you the benefit of decoupling an algorithm from the type it works on. But if you are trying to create a new instance of this type your generic code isn't indepent from this type anymore.

Fortunately there is a solution to the problem known from one of the most referenced books in software engineering - the GOF-Book. It's called Factory Pattern. And with generics the factory pattern is even more powerful. Your factories only need to implement the generic Factory interface


public interface Factory<T> {

public T create();

}


and your generic algorithm can trustfully rely on it.


public class UsingFactory<T> {

Factory<T> factory; // or maybe use Factory<? extends T> factory;

public UsingFactory(Factory<T> factory) {
this.factory = factory;
}

public void someMethod() {
T instance = factory.create();
//...
}

}


Object creation and object using are now decoupled, while the algorithm and the type it works on are decoupled too.

Now you can even implement a class GenericFactory<T> which uses reflection for instantiation. But you don't have to. You aren't forced to use a class with default constructor for T. But generics still work for you and the compiler will complain if the factory type parameter and the type parameter of your algorithm do not match.


// SimpleString creates Strings just like everybody does
Factory<String> simpleStringFactory = new SimpleStringFactory();

UsingFactory<String> useSimple = new UsingFactory<String>(simpleStringFactory);


// instantiates a factory that creates Strings via reflection
Factory<String> stringFactory = new GenericFactory<String>(String.class);

UsingFactory<String> useString = new UsingFactory<String>(stringFactory); // this works like expected

UsingFactory<Long> useLong = new UsingFactory<Long>(stringFactory); //type params do not match; does not compile

Kommentare:

Alex Miller hat gesagt…

You might note that Class now follows this pattern. Class is now Class<T> and is a factory for instances via Class.newInstance().

Richard Metzler hat gesagt…

Thank you for your comment. You are right and I recognized that I had a typo in my post (wrote Class<t> instead of Class<T>).

But you seem to have not read the whole post because I pointed out that it is not good to use Class<T>.newInstance() because there are cases when it fails.

Angelo hat gesagt…

First up, I like your use of the factory pattern: welcome back type safety.

However, in the second code example, the one that uses Class<T> clazz, it is notable that this requires some extra plumbing, i.e., you will need to assign that member in some constructor (since newInstance() is not static, and clazz will be of type Class at runtime anyway).
In the end, this means we will have to pass in the 'real' class, meaning we have a point of failure that will only show up at runtime.

Richard Metzler hat gesagt…

Yes Angelo, that's exactly what I tried to say.

I'll update the examples later.

Thank you for the feedback.

patrick hat gesagt…

The referenced article by Angelika Langer & Klaus Kreft is available online at http://www.angelikalanger.com/Articles/Topics.html#JAVA.

iso775533eac hat gesagt…

我是天山,等待一輪明月。.........................

剩沒底天 hat gesagt…

認識自己,是發現妳的真性格、掌握妳的命運、創照你前程的根源。 ..................................................

陽明山花季 hat gesagt…

thx u very much, i learn a lot

志竹 hat gesagt…

sex性愛85cc性愛紅爺性愛本土美女性愛免費線上性愛電影交友內容同志聊天室ut同志線上看吊帶襪美女圖后工后宮無碼圭賢七年間的愛歌詞圭賢圖片好色貼片區如何延遲射精如何做愛持久如何做愛最爽如何讓女生舒服宅女的幸福生活同志性愛片同志色網站同志色文學交援妹伊莉討論區小說伊莉貼圖區伊莉影片網伊莉論台伊葉情貼片區伊葉情貼圖全國俱樂部0401視訊美女sex女優影音視訊聊天室ut聊天室

少菁 hat gesagt…

nice job! waiting for your new artical. ........................................

韻玉 hat gesagt…

I do like ur article~!!!...................................................

逸凡逸凡 hat gesagt…

thank you for you to make me learn more,thank you∩0∩ ........................................

銘雅婷木 hat gesagt…

成人dvd影城線上免費看成人卡通成人色情電影院色情卡通貼圖色情片免費線上觀賞紅耶紅爺紅爺貼圖紅爺影城紅爺論壇美女圖片免費美女裸体美國色片免費看美國色情片免費觀賞美國色情影片美國免費成人影片美國免費影片美國免費線上a片美國性愛片美國美女圖美國愛買美遊戲美腿a片美腿絲襪性美麗女人國美國色片美國成人影片美國成人片美女影片免費看美女影片免費試看火辣視訊薄紗主播網友自拍露點圖微風成人情色

修強 hat gesagt…

Thx ur share........................................

韋于倫成 hat gesagt…

感謝分享好的作品~~........................................

M12aeganT_Moe12 hat gesagt…

色金激麻館 交友聊天室 藍色情人視訊網 卡通美女a片免費試看 ez自慰台灣 情色 av女優報報,免費試看 18成人avooo,情色 電影 視訊美女ggoo 美女寫真 avdvd一夜情色妹妹免費情慾影片觀賞 hilive免費線上a電影 免費成人片 情人小魔女自拍 網路自拍美女聊天室天堂 美眉 美女 聊天室 遊戲 av女優 av影片 無碼 A片 一夜成人聊天室 sex888 交友網免費視訊聊天 免費視訊聊天mmshow ut 華人影音視訊聊天室 sex女優王國,情色,av 網交甜心 聊天室wewet 免費影片下載 視訊美女jp成人 a片面費下載 台灣成人網 xx18 net影片交流區 免費 a 長片線上看,檳榔西施清涼秀 本土自拍天堂,無碼av女優 情色論壇性愛aa 片 hotsee總站 免費線上視訊fm358 免費a片影片下載 亞洲視訊成人影片論壇 網愛俱樂部 成人圖片區18成人avooo 18 限亞洲禁果影城 拓網免費視訊辣妹脫衣秀 sex免費看影片彩虹論壇 情色視訊交友85cc 視訊美女巨乳34c AV168 成人電影院 免費視訊聊天室捷克論壇 sex888免費影片分享區 UT視訊交友 免費成人影片 bbs論壇,限制級 avsex無碼a片 情色妹

9d5h41dV2h1f2_dgd45 hat gesagt…

不錯唷~我會常常來 >"<..................................................

紫倫妍勳 hat gesagt…

人不可以求其備,必捨其所短,取其所長 ............................................................

宛儒DarwinM_Pawlak0203 hat gesagt…

你不能決定生命的長度,但你可以控制它的寬度..................................................

歐英傑 hat gesagt…

經驗是良師,可惜學費貴..............................

王周宏儒 hat gesagt…

所有的資產,在不被諒解時,都成了負債..................................................

Kath黃rinA俊宇 hat gesagt…

我們不是因為快樂而歌唱,而是唱歌使我們快樂......................................................................

洪筱婷 hat gesagt…

來看看你囉~blog很棒! ...........................................................................

木堯木堯 hat gesagt…

一個人的價值,應該看他貢獻了什麼,而不是他取得了什麼....................................................................

峻帆峻帆峻帆 hat gesagt…

喜歡你的部落格,留言請您繼續加油.................................................................

倩亮倩亮 hat gesagt…

人有兩眼一舌,是為了觀察倍於說話的緣故。............................................................

佳皓佳皓 hat gesagt…

人有兩眼一舌,是為了觀察倍於說話的緣故。............................................................

吳婷婷 hat gesagt…

當一個人內心能容納兩樣相互衝突的東西,這個人便開始變得有價值了。............................................................

穎翰翁穎翰 hat gesagt…

I do like ur article~!!!..................................................................

吳婷婷 hat gesagt…

到處盡心,即為快事;舉步踏實,便是坦途。......................................................

吳婷婷 hat gesagt…

今夜星光多美好~祝你快樂~~~~............................................................

李志杰 hat gesagt…

不妄求,則心安;不妄作,則身安!......................................................

淑慧 hat gesagt…

看到你的好文章真是開心 加油囉~............................................................

淑娟淑娟淑娟 hat gesagt…

獨居時,要反省自己的過錯;在社會大眾之間,則要忘卻別人的過失。..................................................

WillianT_Smotherman0恆迪 hat gesagt…

流浪到這裡,留言謝謝你。..................................................................

鄭信弘 hat gesagt…

做好事,不需要給人知道,雖然只是一件微不足道的事,但我相信,這會帶給我快樂。..................................................

文旺江汝 hat gesagt…

河水永遠是相同的,可是每一剎那又都是新的。. . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

王丁佳燕文均 hat gesagt…

愛,拆開來是心和受兩個字。用心去接受對方的一切,用心去愛對方的所有。......................................................................

宜明文潔 hat gesagt…

說「吃虧就是便宜的人」,多半不是吃虧的人。......................................................................

于庭吳 hat gesagt…

臨淵羨魚,不如退而結網。......................................................

v惠王王王娟 hat gesagt…

Never put off till tomorrow what may be done today..................................................................

1615 hat gesagt…

請繼續發表好文!加油加油再加油!............................................................

淑蕙春蕙春芬 hat gesagt…

大肚能容,了卻人間多少事,滿腔歡喜,笑開天下古今愁。..................................................

幸平平平平杰 hat gesagt…

認識自己,是發現妳的真性格、掌握妳的命運、創照你前程的根源。............................. ....................................

誠林法宇法宇紋 hat gesagt…

被你的人氣吸引過來~~.................................[/url]...............

惠NorrisBradwell041花 hat gesagt…

朋友是一面鏡子......................................................................

Cool hat gesagt…

Thanks very nice share ... I follow your site constantly ... değiniyorsunuz important issues ... Congratulations ... I entered this site by chance, but I found very interesting. Seni Bana Yazmışlar A greeting to all the people who visit this page. Kuzey Ve Güney "The powers delegated by the proposed Constitution to the federal government are few and defined. Those which are to remain in the State governments are numerous and indefinite. Yalan Dünya " -Madison Federalist Papers

seni bana yazmışlar hat gesagt…

Thanks very nice share ... I follow your site constantly ... important issues ... Congratulations ... I entered this site by chance, but I found very interesting. Seni Bana Yazmışlar A greeting to all the people who visit this page. Kuzey Ve Güney "The powers delegated by the proposed Constitution to the federal government are few and defined. Those which are to remain in the State governments are numerous and indefinite.