Reputation: 11025
How can I mention the path of a class as in following code?
Class cl=Class.forName("SomeClass");
This works well if the "SomeClass" is located in the same directory of the calling class. But how to check for a class from a different directory, I saw the syntax for that is like xxxx.yyyy.class
, but could not make out what those 'x's and'y's stand for. please help.
Thanks in advance.
Upvotes: 0
Views: 296
Reputation: 15552
Use Class.forName although make sure you deal with a possible ClassNotFoundException exception. This is a runtime exception so it does not mean you need to catch it. This is how you will know if you path to the class is correct. The problem is that if it cannot find the class funny things can happen with your code.
Class.forName(com.my.package.ClassName)
Upvotes: 0
Reputation: 5744
Those xxx
and yyy
stands for package names. Packages are normally represented by directories on disk with the same name as the package. When you create a class file you can specify which package the class goes by stating package xxx.yyy
at the top of the file.
Referring to "SomeClass"
without a package name will try to load a class named SomeClass
in the default package.
Upvotes: 1
Reputation: 359786
Use the fully-qualified class name. For instance, to do this with the Java SE String
class, which is in the java.lang
package:
Class clazz = Class.forName("java.lang.String");
Upvotes: 3