The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
August 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

create object of class

Posted by anvar bakenov on August 29, 2000 at 4:50 PM

> Hi Gavin
> You can create an object of a class from the class reference in java. You have to use reflection to do it. There are three classes through them you can query the class reference , create an object using any constructor passing arguments, invoke any methods and many more... The classes are Constructor, Method, Field. They are in java.lang.reflect package. I have written a simple example to show you how to get an object if you have a class reference. Only thing that you have to take care is that getObject () ( in my code below ) always returns an object of class Object. So you have to downcast the resulting object to appropriate type. I think it will be better if you use a class like GetObjectFromClass to create an object and then use Factory design pattern which will call getObject () method on GetObjectFromClass class and then typecast the resulting object to appropriate class. This way it will be easy for programmer to create an object of a particular class ( he won't have to typecast everywhere ). Again you can create a method getObject ( String className ) where you accept a string which is a class name and then call getObject ( Class c ) using Class.forName ( classname ) method. To create an object this way you must declare a default constructor which should be public otherwise ( if you call getDeclaredConstrcutors() which returns all types of constrcutor including private ones ) you must call setAccessible ( true ) on the constructor you are calli if you are calling a non-public constructor..
> Following example may be helpfull.
> Thanx
> Kishori

> /////////////DelphiToJava.java///////////////////
> import java.lang.reflect.* ;

> /* This class methods have been declared static. When you pass a class
> reference to one of the methods it creates an object of that class type
> and returns that object. However, the object returned has a type of Object
> and you have to apply downcast in your code to use that object of a particular
> type */
>
> class GetObjectFromClass {
> public static Object getObject ( Class classref ) {
>
> // Check for valid class reference
> if ( classref == null ) return null ;
>
> // Since this method is called when you want to
> // create an object of a class using its default constructor
> // you must declare a default constructor in your class and
> // declare it public.If you don't declare it public then
> // yuo have to tweak the security settings.

> try {
> Object o = classref.newInstance () ;
> return o ;
> } catch ( Exception e ) {
> return null ;
> }
>
> }
>
> public static Object getObject ( Class classRef , Object[] args ) {
>
> // Check for valid class reference
> if ( classRef == null || args == null ) return null ;
>
> Object o = null;
>
> /* You can create an object from a class reference passing arguments
> to the constructor of that class using an object of class Constructor */
>
> try {
> /* Get the class type of all the arguments passed and store them
> in an array which will be used to find out the matching constructor */
> Class[] argsClass = new Class[args.length];
> for ( int i = 0 ; i < args.length ; i++ )
> argsClass[i] = args[i].getClass ( );
>
> // Get the constructor of the class matching the arguments passed
> Constructor con = classRef.getConstructor ( argsClass ) ;
>
> // Create an object using the constructor
> if ( con != null )
> o = con.newInstance ( args ) ;
> else
> System.out.println ( " Constructor is returning null" ) ;
> return o ;
> } catch ( Exception e ) {
> e.printStackTrace ( );
> return null ;
> }
> }
> }

>
> /* These classes are for demo purpose only. There are three classes inherting
> one from another. These classes will be used in DelphiToJava class to
> demonstrate the concept of creating an object after getting the class
> reference */
>
> class A1 {
> private String name = "" ;
> public A1 ( ) {
> name = "NO Name" ;
> }
> public A1 ( String name ) {
> this.name = name ;
> }
>
> public String getValue ( ) {
> return name ;
> }
> }

> class A2 extends A1 {
> public A2 ( ) {
> super() ;
> }
> public A2 ( String name ) {
> super ( name + " ... from A2" ) ;
> }
> }

> class A3 extends A2 {
>
> public A3 ( ) {
> super ( );
> }
> public A3 ( String name ) {
> super ( name + " ... from A3" ) ;
> }

> }


> public class DelphiToJava {
> public static void main ( String[] args ) {
>
> Class c = null ;
>
> // Create object using default constructor
> try {
> // Create a class reference
> c = Class.forName ( "A1" ) ;
>
> // Create an obejct from class reference. Please note that
> // you have to cast the return value of getObject ( ).
> A1 a = ( A1 ) GetObjectFromClass.getObject ( c ) ;
> if ( a != null )
> System.out.println ( "Name = " + a.getValue ( ) );
> else
> System.out.println ( "Could not create the object" );
>
> } catch ( Exception e ) {
> System.out.println ( "Class \"A1\" could not be found" ) ;
> }
>
>
> // Create object using constructor passing an integer value
> try {
> // Create a class reference
> c = Class.forName ( "A3" ) ;

> /* Create an object from class reference */
> /* Prepare the arguments array. For primitive types
> ( in our case it is int ) you have to use wrapper classes */
> Object[] objArgs = { "Kishori" } ;
> A3 aa = ( A3 ) GetObjectFromClass.getObject ( c, objArgs ) ;
> if ( aa != null )
> System.out.println ( "Name = " + aa.getValue ( ) );
> else
> System.out.println ( "Could not create the object" );

> } catch ( Exception e ) {
> System.out.println ( "Class \"A3\" could not be found" ) ;
> }

>
>
> }
> }






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us