Reputation: 19
How can I generalize the following code:
String nameString = "myClass_t";
myClass_t myVar = (myClass_t) AnotherClass.classMethod();
The return type of AnotherClass.classMethod() needs to be obtained from a file (thus a String variable). The type of myVar needs to match that type.
How can I rewrite the 2nd line to enable it to get the type from nameString?
Thank you so much for your help.
Upvotes: 1
Views: 2109
Reputation: 44205
Use an instance of Class:
Class<?> myclass = Class.forName("myClass_t");
myClass_t myVar = (myClass_t)myclass.cast(AnotherClass.classMethod());
Be aware that this might throw several Exceptions, e.g. if the class defined by the string does not exist or if AnotherClass.classMethod() doesn't return an instance of the class you want to cast to. To clarify the interface idea (which is usally used for plugin mechanisms in Java):
interface Testing {
public String getName();
}
class Foo implements Testing
{
public String getName()
{
return "I am Foo";
}
}
class Bar implements Testing
{
public String getName()
{
return "I am Bar";
}
}
// Then
Class<?> myclass = Class.forName("Foo");
Testing instance = (Testing)myclass.newInstance();
System.out.println(instance.getName()); // I am a Foo
myclass = Class.forName("Bar");
Testing instance = (Testing)myclass.newInstance();
System.out.println(instance.getName()); // I am a Bar
Basically you have a dynamic class name (e.g. from a properties file). This class implements an interface, so you can make sure that class instances provide the interfaces methods (instead of using reflection for everything).
Upvotes: 2
Reputation: 269657
This doesn't make a lot of sense. If the type of myVar
is not statically known, you will only be able to use it via reflection. In that case, just store it as an Object
.
Are you trying to verify that classMethod()
is returning the expected type? Or are you trying to cast the result to a specific type so that you can invoke specific methods on it? In other words, what are you going to do with myVar
next? Invoke a method like myVar.myMethod()
?
Here's an example of invoking a method on an object using reflection. Refer to the Class
documentation for a more detailed explanation.
Object myVar = AnotherClass.classMethod();
/* Get the class object for "myVar" to access its members. */
Class<?> myClass = myVar.getClass();
/* Find the public, no-arg method "myMethod()". */
Method mth = myClass.getMethod("myMethod");
/* Invoke "myMethod()" on "myVar", and assign result to "r". */
Object r = mth.invoke(myVar);
Upvotes: 2