If I have a String "Hello" and I know it is a name of a class, how to use it to create a object?

F

fAnSKyer

If I have a String "Hello" and I know it is a name of a class, how to
use the string to create a object?

Thanks, fAn
 
A

Andrew Thompson

fAnSKyer said:
If I have a String "Hello" and I know it is a name of a class, how to
use the string to create a object?

Reflection. But what actual general problem are
you attempting to solve?

Using reflection in Java is generally considered a
poor hack (though some types of applications
need to use it extensively - like servers).

Andrew T.
 
F

fAnSKyer

A following question,
It can run, but IF the class "Hello" have a method get();

using o.get() is wrong. Because it is a Object, not a Class. How to
solve then?


Thanks a lot
Fans.

Thomas Schodt 写é“:
 
D

Dijon Yu

fAnSKyer said:
A following question,
It can run, but IF the class "Hello" have a method get();

using o.get() is wrong. Because it is a Object, not a Class. How to
solve then?
If method get() is not a static method, you must create a instance of
Hello class, you use Object o =
Class.forName(classname).newInstance();
like Thomas Schodt write
Dijon Yu
 
T

Thomas Schodt

fAnSKyer said:
A following question,
It can run, but IF the class "Hello" have a method get();

using o.get() is wrong. Because it is a Object, not a Class. How to
solve then?

You either need to know about the class (which defeats the purpose)
or it needs to implement a known interface


interface KnownInterface {
Object get();
}

class UnknownClass implements KnownInterface {
Object get() {
// ...
}
}


String classname = "UnknownHello";
Object o = Class.forName(classname).newInstance();
KnownInterface ki = (KnownInterface)o;
Object ret = ki.get();


or you need to get serious with reflection - read
<http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/package-summary.html>
 
F

fAnSKyer

Thanks a lot.

What if KnownInterface is also a String and I need use this String to
do the following steps?
Still need help.

Thanks, fAns.
Thomas Schodt 写é“:
 
S

su_dang

fAnSKyer said:
A following question,
It can run, but IF the class "Hello" have a method get();

using o.get() is wrong. Because it is a Object, not a Class. How to
solve then?


Thanks a lot
Fans.

Thomas Schodt 写é“:

Using reflection, you can obtain an object of the class Method which
can be used to invoke the method you want.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top