You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@struts.apache.org by temp temp <mi...@yahoo.com> on 2007/02/09 23:09:29 UTC
[JAVA] creating instance of the class
I want to create instance of a class using object.getClass().new Instance() but this object constructor needs another object so how can I do this ?
Suppose I have a class
DefaultMetaInfoHandler default=new DefaultMetaInfo(test);
Can I create instance of this class using default.getClass().newInstance()
If I have to create how ?
Thanks
Miro
---------------------------------
Check out the all-new Yahoo! Mail beta - Fire up a more powerful email and get things done faster.
Re: [JAVA] creating instance of the class
Posted by Niall Pemberton <ni...@gmail.com>.
On 2/9/07, temp temp <mi...@yahoo.com> wrote:
> I want to create instance of a class using object.getClass().new Instance() but this object constructor needs another object so how can I do this ?
>
>
> Suppose I have a class
>
> DefaultMetaInfoHandler default=new DefaultMetaInfo("test");
>
> Can I create instance of this class using default.getClass().newInstance()
You can't - you have to get hold of the constructor that has the
single argument and invoked it. So using your example - a constructor
that takes a single String parameter:
Class clazz = DefaultMetaInfo.class;
Classs[] paramTypes = new Class[] {String.class};
// Get the constructor
Constructor ctor = clazz.getConstructor(paramTypes);
// Create a new instance
Object[] args = new Object[] {"test"};
DefaultMetaInfoHandler default =
(DefaultMetaInfoHandler)ctor.newInstance(args)
BeanUtils has convenience methods to do this - including one for a
constructor that takes a single argument:
http://tinyurl.com/2hgkrm
So using BeanUtils al you need to do is:
DefaultMetaInfoHandler default = (DefaultMetaInfoHandler)
ConstructorUtils.invokeConstructor(DefaultMetaInfo.class,
"test");
Niall
> If I have to create how ?
>
> Thanks
> Miro
---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org