Re: instantiate class from string



sarath wrote:
1.

I have a method,

public void something(String fullyQualifiedClassName)
{
}

the parameter passed to the method is a fully qualifed class name for a
class. I have to instantiate that very same class inside the method.
how can u do it ?


Here is an example that should get you started:

//--- CreateObject.java
public class CreateObject {

    public static class SomeClass {
        public void sayHello() {
            System.out.println("Hello!");
        }
    }

    public static Object createObject(String className)
            throws ClassNotFoundException, InstantiationException,
            IllegalAccessException {
        return Class.forName(className).newInstance();
    }

    public static void main(String[] args) {
        try {
            Object o = createObject("CreateObject$SomeClass");
            if (o instanceof SomeClass) {
                ((SomeClass) o).sayHello();
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        } // nb. you'll really want to catch the exceptions.
    }
}
//---


2. Why string is immutable which is an additional overhead ?


There are a number of reasons why java.lang.String is immutable. Thread safety is sometimes important. I think the API docs do a so-so job of explaining why you might want an immutable String:


http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html

thanks in advance

sarath



--
Peter MacMillan
e-mail/msn: peter@xxxxxxxxxxxxx
.



Relevant Pages

  • Re: Dynamic Class loading and if () statements
    ... would this work even if SomeClass could ... This may pose a problem. ... of an effort to instantiate the class, and do away with the test. ... > required for one plugin to work. ...
    (comp.lang.java.help)
  • Re: UML "OR" Composition Question
    ... one must not instantiate X? ... E.g. one may start with a class Exception. ... that there are existing references to Exception. ...
    (comp.object)
  • Re: baffled by exception
    ... > latter emulate the former? ... and it's driving me insane - I can't work out what's> wrong ... > It just seems to throw an exception, citing 'User Breakpoint' as the cause> of the exception when any C++ code tried to instantiate it. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: baffled by exception
    ... > latter emulate the former? ... and it's driving me insane - I can't work out what's> wrong ... > It just seems to throw an exception, citing 'User Breakpoint' as the cause> of the exception when any C++ code tried to instantiate it. ...
    (microsoft.public.dotnet.languages.vc)
  • Re: baffled by exception
    ... > latter emulate the former? ... and it's driving me insane - I can't work out what's> wrong ... > It just seems to throw an exception, citing 'User Breakpoint' as the cause> of the exception when any C++ code tried to instantiate it. ...
    (microsoft.public.vc.language)