• Post Reply Bookmark Topic Watch Topic
  • New Topic

Class.forName() question  RSS feed

 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to get a Class name from a properties file and wanna call a static method inside that class. I dont wanna use reflection....here is what i tried and it didnt work
import java.math.*;
import java.lang.Math;
class IntegerTrial
{
public static void main(String[] args)
{
try{
Class fo = Class.forName("java.lang.Math") ;
System.out.println(fo.PI);
}catch(Exception e){System.out.println(e);}
}
}
Please suggest whats wrong and how to make it work ?
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have to use reflection, sorry. Since you're loading the class at runtime, you have to look up the method at runtime -- in this code you're asking the compiler to do it, and the compiler can't, since it doesn't know what class to look in!
 
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you're stuck. You would have to cast fo to something with a public PI variable to make the compiler happy. And the cast syntax wants the very class you're casting to, which what you're trying to avoid having.
I'm curious why you need to abstract java.lang.Math out to a property value. Are there other "PI providers" that you can plug in? Do they all have some common interface or ancestor? If so, you could cast to the common type and use PI. (I'm guessing NO because Math extends Object, implements no interfaces, and is final.)
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!