Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!.POSTED!not-for-mail From: BGB Newsgroups: comp.lang.java.programmer Subject: Re: Define Type at runtime Date: Thu, 08 Sep 2011 11:07:41 -0700 Organization: albasani.net Lines: 50 Message-ID: References: <4e678737$1@news.x-privat.org> <5a51c17a-6488-492c-bad4-857a622f5c46@glegroupsg2000goo.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.albasani.net ii45hIsa3x7TjJC2oZ7VmdNP3zvXbj97BIkCVTYl8noeOvmi8doq0IRiVWiJ8sOFz0ko8z8U+b38mpf0EXKCXQ== NNTP-Posting-Date: Thu, 8 Sep 2011 18:07:40 +0000 (UTC) Injection-Info: news.albasani.net; logging-data="FtuvcH2PXZqCYk9l779ZedyfaCGNd7+Ee1DZ1EGNnD0QAeRKbjxiPbMb68eLEFFxuz/QPLzxmQfgl95qtOHYAOhhiCawDaParBh/fANdu/2Tt0ngJa00DraLBEGtv9Ng"; mail-complaints-to="abuse@albasani.net" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20110902 Thunderbird/6.0.2 In-Reply-To: <5a51c17a-6488-492c-bad4-857a622f5c46@glegroupsg2000goo.googlegroups.com> Cancel-Lock: sha1:XiPu1dXbSIroIMWmAgivfHhd1vE= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:7705 On 9/8/2011 9:32 AM, Lew wrote: > John wrote: >> If I have a method: >> public void someMethod(Object o){ >> ... >> Entity entity; >> .... >> } >> >> How could I define at runtime the type T if I have an Object? > > You can do an illegal cast with the help of '@SuppressWarnings("unchecked")' and a 'catch ( ClassCastException exc )'. > > You can under certain circumstances use a run-time type token of type 'Class'. > > You can write your method to be type-safe in the first place and avoid the problem. > > Without some context we can't know what you really want. Your question is far too non-specific. > and, probably, not to forget "instanceof". eg, rather than, say: Object obja; try { SomeObject objb=(SomeObject)obja; ... }catch(ClassCastException ex) { } one could be like: if(obja instanceof SomeObject) { SomeObject objb=(SomeObject)obja; ... } which could be more useful if one wants to do the types N-way... if(...) { ... }else if(...) { ... }else ... or such...