Re: instantiate class from string
- From: Peter MacMillan <peter@xxxxxxxxxxxxx>
- Date: Fri, 29 Apr 2005 02:39:36 -0400
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 .
- Follow-Ups:
- Re: instantiate class from string
- From: raghupulikkal
- Re: instantiate class from string
- References:
- instantiate class from string
- From: sarath
- instantiate class from string
- Prev by Date: Re: Java StreamTokenizer
- Next by Date: Re: difference in javascript execution
- Previous by thread: instantiate class from string
- Next by thread: Re: instantiate class from string
- Index(es):
Relevant Pages
|
|