The Artima Developer Community
Sponsored Link

Java Answers Forum
How to make an instance of a class from a string?

3 replies on 1 page. Most recent reply: Mar 10, 2002 2:24 AM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 3 replies on 1 page
Avin Sinanan

Posts: 28
Nickname: avin
Registered: Feb, 2002

How to make an instance of a class from a string? Posted: Mar 9, 2002 9:13 PM
Reply to this message Reply
Advertisement
Hello I posted a similar question today. I got some replies..thanks !
However I came across a similar problem.
The code below tries to create an instance of a class from a string. That is .. whatever the name of the String is that is what the name of the instancve of the class will be. The code is obviouly not compling.. can anyone take a look at it and make it work. Thanks a million!

here it is -->

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
 
class Test
{
	public static void main(String[] args)
	{  	
		int count =0;
		String link1 = Integer.toString(count);
		Link link1 = new Link();
		
		count++ ;
		String link1 = Integer.toString(count);
		Link link1 = new Link();
		
		for(int i = 0 ; i<1 ; i++)
		{
			link1.method1(i);
		}
		
		for(int j = 1 ; j<2 ; j++)
		{
			link2.method1(j);
		}
		
		
	}
}
 
 
class Link
{
	int number1 = 0 ;
	
	public Link()
	{
	}
	
	public void method1(int number)
	{
		number1 = number1 + number ;
		System.out.println(number1);
		JFrame frame = new JFrame("hi");
		
		frame.setSize(300,300);
		frame.setVisible(true);
	}
}


Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: How to make an instance of a class from a string? Posted: Mar 9, 2002 10:35 PM
Reply to this message Reply
I'm not sure if I correctly understand your qustion, in the context of the code you are including, but here is some code to demonstrate how you instantiate an object based upon its name:
public class ForName
{
    public static void main(String [] args)
    {
        Object ob = null;
        try
        {
            ob = Class.forName(args[0]).newInstance();
            System.out.println( "Instantiated an object called \"" + ob.getClass().getName() + 
                                 "\", it's toString() gives: " + ob.toString() );
        }
        catch(ArrayIndexOutOfBoundsException aioobe)
        {
            System.out.println( "Specify the name of the class you want to instantiate!" );
        }        
        catch(ClassNotFoundException cnfe)
        {
            System.out.println( "Can't find a class called \"" + args[0] + "\", try one that exists!" );
        }    
        catch(InstantiationException ie)
        {
            System.out.println( "Failed to instantiate class \"" + args[0] + "\", try another!" );
        }    
        catch(IllegalAccessException iae)
        {
            System.out.println( "Sorry, pal, you are not allowed to instantiate a \"" + args[0] + "\", try another!" );
        }    
        
    }                            
}
 
class TestClass
{
    public TestClass()
    {
        System.out.println( "Created a " + this.getClass().getName() );
    }
    public String toString()
    {
        return "I'm a TestClass object!";
    }
}
 
class AnotherTestClass
{
    public AnotherTestClass()
    {
        System.out.println( "Created a " + this.getClass().getName() );
    }
    public String toString()
    {
        return "I'm a AnotherTestClass object!";
    }
}


You can experiment with it by running it with any class name (fully qualified) that you can think of. Here are some examples:

C:\temp>java ForName java.util.ArrayList
Instantiated an object called java.util.ArrayList, it's toString() gives: []

C:\temp>java ForName java.util.ArrayList
Instantiated an object called "java.util.ArrayList", it's toString() gives: []

C:\temp>java ForName TestClass
Created a TestClass
Instantiated an object called "TestClass", it's toString() gives: I'm a TestClass object!

C:\temp>java ForName java.security.spec.X509EncodedKeySpec
Failed to instantiate class "java.security.spec.X509EncodedKeySpec", try another!

C:\temp>java ForName java.util.Random
Instantiated an object called "java.util.Random", it's toString() gives: java.util.Random@3e86d0


Note that it can fail to create classes for a number of reasons: if it is abstract, an interface, doesn't have a default constructor, or has a private one, etc.

You may want to add more detail to the exception handling, if you want to understand better why a particular class fails to be instantiated.

Avin Sinanan

Posts: 28
Nickname: avin
Registered: Feb, 2002

Re: How to make an instance of a class from a string? Posted: Mar 10, 2002 1:03 AM
Reply to this message Reply
Ok lets see how best I can explain what am trying to do.
Ok lets put it this way.. I have 5 classes.
3 of the five classes generate a set of X and Y values that each can be used to plot a graph.
These 3 classes run in Parallel using a discrete
event simulation technique.

The 4th class is a dynamic array class.
Now this 4th class stores the values generated by each of the 3 classes. Of course each of the 3 classes makes an individual instance of the 4th class. This in not a problem. Everything is cool up to there.

The problem is the 5th class actually draws the graph. You see I can program each of the first 3 classes to make an instance of the 4th class. But how does the 4th class make an instance of the 5th class. Each instance of the 4th class must make a difereent instance of the 5th class.

So what I proposed to do was implnemnt a counter. Each time an instance of the 4th class was made it made an instance of the 5th class with the name 1 will be made. The counter was then incremented. SO if another instance of the 4th class was made then an instance of the 5th class named 2 would be made.

That is that I was trying to do with the code I printed before.

Am I making any sense? If am not please let me know and I'll see if i can explain it better.

Hey thanks for all the help so far ...

yours respectfully Avin Sinanan

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: How to make an instance of a class from a string? Posted: Mar 10, 2002 2:24 AM
Reply to this message Reply
I don't think I understand. If one class always wants to create another, then it simply contains an instance variable, something like this:

class Renderer { /* ... */ }
class PointCollector
{
    private Renderer myRenderer = new Renderer();
    // ...
}

Now every instance of the PointCollector class that you instantiate will have its own (different) Renderer.

I don't see why it would make a difference whether the instances of the Renderer class have a name, or not, for this particular purpose.

When you talk about classes doing things, I assume you really mean instances of these classes doing things.

Flat View: This topic has 3 replies on 1 page
Topic: Indention & Comments Previous Topic   Next Topic Topic: Serial Port Manipulation with Visual J++, any chance?

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use