Java Mailing List Archive

http://www.junlu.com/

Home » Home (12/2007) » Struts 2 »

Re: [JAVA] creating instance of the class

Niall Pemberton

2007-02-09

Replies:

On 2/9/07, temp temp <miroconnect@(protected):
>   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@(protected)
For additional commands, e-mail: user-help@(protected)

©2008 junlu.com - Jax Systems, LLC, U.S.A.