• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to check whether a class exist dynamically?  RSS feed

 
O. Subramaniam
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys,
write a program to check whether a class exist or not?
if exist load that into memory so that they can be instantiated.
this question was asked in an interview. and i dont know how to do it.
please help me guys.
thanx in advance
regards
o. subramaniam
 
Chinmay Bajikar
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try and see
wht Class.forName(String classname) does.
It comes in java's replection abilities.
let me know if it helped.
 
Phil Chuang
Ranch Hand
Posts: 251
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you could do this:
-----
try
{
Class cls = Class.forName ("com.somepackage.SomeClass");
// check java api for Class object for details on instantiating w/ default constructor
}
catch (ClassNotFoundException e)
{
// blah
}
-----
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just create a file giving that path and check whether that file exists or not.
File fileTest=new File("path/ClassName.class");
if(fileTest.exists()){
System.out.println("exists");
//Instantiate the class.
} else {
System.out.println("not exists");
}
 
Avi Abrami
Ranch Hand
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mathews,

just create a file giving that path and check whether that file exists or not

Do you know if that works if the class is in a JAR file?
Avi.
 
Phil Chuang
Ranch Hand
Posts: 251
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope, won't work if the class is in a jar, whereas if you use the code I posted earlier, you won't have to look for a class, the JVM's classloaders will look for it, and throw an exception if it doesn't find it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!