By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,786 Members | 1,143 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,786 IT Pros & Developers. It's quick & easy.

absolute .class file name to java class name

P: n/a
the java.lang.Object.forName method takes a java class name and returns a
Class object associated with that class.
eg. Class myClass = Object.forName("java.lang.String");

by if i only know the absolute file name of a .class file eg.
C:\myJava\myApp.java, then how do i translate this file name to a java class
name the Object.forName method would accept has it's parameter?
thanks,
fu bo
Jul 17 '05 #1
Share this Question
Share on Google+
8 Replies


P: n/a
Fu Bo Xia wrote:
the java.lang.Object.forName method takes a java class name and returns a
Class object associated with that class.
eg. Class myClass = Object.forName("java.lang.String");

by if i only know the absolute file name of a .class file eg.
C:\myJava\myApp.java, then how do i translate this file name to a java class
name the Object.forName method would accept has it's parameter?


Fu Bo,

Do you have a class file or a java source file? If you have the java
source file, there were just a couple of Java Tech tips from Sun
concerning how to compile and load a class. Check their web site.

If you really have a class file, then you need for the directory
containing the class file to be in the classpath (set by the CLASSPATH
variable or by the -classpath option to the java executable) assuming
the class is in the default package. If the class is in a package, e.g.
com.xxx.MyClass, and the class file is in
C:\myJava\com\xxx\MyClass.class, then the directory C:\myJava should be
added to the classpath.

If you do not have the option of modifying the classpath, you can load
the file into an array of bytes and the Java API provides a means of
loading the bytes as a class. See the java.lang.Class and
java.lang.ClassLoader APIs.

HTH,
Ray

Jul 17 '05 #2

P: n/a
thanks ray,

sorry i meant .class files not .java files.

let clearify my problem:

my application is given the absolute file name of a .class file eg.
C:\myJava\myApp.class during run time (via command line or file selection
dialog box.)
how can i use this class? ie. instantiate it or use java.lang.refect tools
on it.
thanks,
fu bo

Fu Bo,

Do you have a class file or a java source file? If you have the java
source file, there were just a couple of Java Tech tips from Sun
concerning how to compile and load a class. Check their web site.

If you really have a class file, then you need for the directory
containing the class file to be in the classpath (set by the CLASSPATH
variable or by the -classpath option to the java executable) assuming
the class is in the default package. If the class is in a package, e.g.
com.xxx.MyClass, and the class file is in
C:\myJava\com\xxx\MyClass.class, then the directory C:\myJava should be
added to the classpath.

If you do not have the option of modifying the classpath, you can load
the file into an array of bytes and the Java API provides a means of
loading the bytes as a class. See the java.lang.Class and
java.lang.ClassLoader APIs.

HTH,
Ray

Jul 17 '05 #3

P: n/a
On Mon, 1 Sep 2003 12:07:09 +1000, "Fu Bo Xia" <fu****@optushome.com.au>
two-finger typed:
thanks ray,

sorry i meant .class files not .java files.

let clearify my problem:

my application is given the absolute file name of a .class file eg.
C:\myJava\myApp.class during run time (via command line or file selection
dialog box.)
how can i use this class? ie. instantiate it or use java.lang.refect tools
on it.
Reflection is the only way, since you have the class name only in a string.

Since the class file needs to be found through the classpath, you could try
setting the java.class.path system property, and then use reflection to
load the class, the byte loading method explained below.

Cheers.


thanks,
fu bo

Fu Bo,

Do you have a class file or a java source file? If you have the java
source file, there were just a couple of Java Tech tips from Sun
concerning how to compile and load a class. Check their web site.

If you really have a class file, then you need for the directory
containing the class file to be in the classpath (set by the CLASSPATH
variable or by the -classpath option to the java executable) assuming
the class is in the default package. If the class is in a package, e.g.
com.xxx.MyClass, and the class file is in
C:\myJava\com\xxx\MyClass.class, then the directory C:\myJava should be
added to the classpath.

If you do not have the option of modifying the classpath, you can load
the file into an array of bytes and the Java API provides a means of
loading the bytes as a class. See the java.lang.Class and
java.lang.ClassLoader APIs.

HTH,
Ray


Jul 17 '05 #4

P: n/a
i've tried the following for creating a java.lang.Class object for
c:\myJava\myApp.class

//set system property java.class.path
String currentCP = System.getProperty("java.class.path").toString();
System.setProperty("java.class.path", (currentCP + ";" +
"C:\\myJava"));
//set system property java.library.path
String currentLP =
System.getProperty("java.library.path").toString() ;
System.setProperty("java.library.path", (currentLP + ";" +
"C:\\myJava"));
//set system property java.ext.dirs
String currentED = System.getProperty("java.ext.dirs").toString();
System.setProperty("java.ext.dirs", (currentED + ";" +
"C:\\myJava"));

//create Class object
Class myClass = Class.forName("myApp");
but the Class.forName method is still throwing ClassNotFoundException
any suggestions?

fu bo

"Neomorph" <ne******@nospam.demon.co.uk> wrote in message
news:j4********************************@4ax.com...
On Mon, 1 Sep 2003 12:07:09 +1000, "Fu Bo Xia" <fu****@optushome.com.au>
two-finger typed:

Reflection is the only way, since you have the class name only in a string.

Since the class file needs to be found through the classpath, you could try
setting the java.class.path system property, and then use reflection to
load the class, the byte loading method explained below.

Cheers.

Jul 17 '05 #5

P: n/a
On Tue, 2 Sep 2003 15:40:45 +1000, "Fu Bo Xia" <fu****@optushome.com.au>
two-finger typed:
i've tried the following for creating a java.lang.Class object for
c:\myJava\myApp.class

//set system property java.class.path
String currentCP = System.getProperty("java.class.path").toString();
System.setProperty("java.class.path", (currentCP + ";" +
"C:\\myJava"));
Change the ";" into File.pathSeparator to keep it cross-platform.
//set system property java.library.path
String currentLP =
System.getProperty("java.library.path").toString( );
System.setProperty("java.library.path", (currentLP + ";" +
"C:\\myJava"));
Only neccessary when the class you want to load is using a native library.
//set system property java.ext.dirs
String currentED = System.getProperty("java.ext.dirs").toString();
System.setProperty("java.ext.dirs", (currentED + ";" +
"C:\\myJava"));
When there's a JAR file in the directory, but you could add that into the
classpath directory as well.

I wonder if there is a way to reinitialize the classloader after these
changes ? And if it's neccessary to do that for what you're trying to do
here...

//create Class object
Class myClass = Class.forName("myApp");
but the Class.forName method is still throwing ClassNotFoundException
any suggestions?
Raymond mentioned loading the bytes as a class: Raymond DeCampo <rd******@twcny.rr.com> wrote:
If you do not have the option of modifying the classpath, you can load
the file into an array of bytes and the Java API provides a means of
loading the bytes as a class. See the java.lang.Class and
java.lang.ClassLoader APIs.

You probably need to write your own classloader.

Do you actually have the API Documentation ?
It's usually a seperate download from Sun's website, but there is also a
Window Helpfile implementation of several JDK versions API's:
http://www.confluent.fr/javadoc/javadoce.html

fu bo

"Neomorph" <ne******@nospam.demon.co.uk> wrote in message
news:j4********************************@4ax.com.. .
On Mon, 1 Sep 2003 12:07:09 +1000, "Fu Bo Xia" <fu****@optushome.com.au>
two-finger typed:

Reflection is the only way, since you have the class name only in a string.

Since the class file needs to be found through the classpath, you couldtry
setting the java.class.path system property, and then use reflection to
load the class, the byte loading method explained below.

Cheers.


Jul 17 '05 #6

P: n/a
Fu Bo,

OK, I broke down and did it, just to make sure it could be done. The
code is really raw and needs to be cleaned up greatly, but I'll leave
that to you.

Here's the output (you'll have to adjust to Windows, I'm on Linux):

$ java -cp . LoadClassFromFile tmp/HelloWorld.class
Hello World!
$

Real exciting huh? I'll leave the HelloWorld class as an exercise, but
here's the LoadClassFromFile class:

////// BEGIN LoadClassFromFile.java
import java.io.*;
import java.lang.reflect.*;

public class LoadClassFromFile
{
public static void main(String[] args) throws Exception
{
for (int i = 0; i < args.length; i++)
{
Class klass = loadClass(args[i]);
Method main = klass.getMethod("main", new Class[]
{String[].class});
main.invoke(null, new Object[] {new String[0]});
}
}

private static Class loadClass(final String filename) throws
ClassNotFoundException
{
ClassLoader loader = new ClassLoader()
{
protected Class findClass(String name) throws
ClassNotFoundException
{
// Always load the file
InputStream in = null;
try
{
in = new BufferedInputStream(new
FileInputStream(filename));
ByteArrayOutputStream byteStr = new
ByteArrayOutputStream();
int byt = -1;
while ((byt = in.read()) != -1)
{
byteStr.write(byt);
}
byte byteArr[] = byteStr.toByteArray();
return defineClass(null, byteArr, 0, byteArr.length);
}
catch (final RuntimeException rex)
{
throw rex;
}
catch (final Exception ex)
{
ex.printStackTrace();
throw new ClassNotFoundException(name);
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (final IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
};
return loader.loadClass("garbage");
}
}
///// END LoadClassFromFile.java

Again, this code needs a lot of work, but it should give you the basic idea.

Ray

Jul 17 '05 #7

P: n/a
thanks ray, this baby works like a charm : )
i used your codes to write a customer implementation of ClassLoader:

//start of ClassFileLoader.java
import java.io.*;
import java.lang.reflect.*;

/**
* A custom implementation of ClassLoader that loads class by it's file
name.
*
* use the loadClass(String classFileName) method to return a
java.lang.Class object
* for the class identified by classFileName, the classFileName can be
relative or
* absolute file name eg. C:\myJava\myApp.class
*/
public class ClassFileLoader extends ClassLoader{

public static void main(String[] args) throws Exception {

final String Usage = "USAGE: java ClassFileLoader [class files...]";

if (args.length > 0) {

for (int i = 0; i < args.length; i++)
{
Class klass = new ClassFileLoader().loadClass((args[i]));
System.out.print(klass.getName());
}
} else {
System.out.println(Usage);
}
}

/**
* original code by Raymond DeCampo <rd******@twcny.rr.com>
*/
protected Class findClass(String fileName) throws ClassNotFoundException {

// Always load the file
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(fileName));
ByteArrayOutputStream byteStr = new ByteArrayOutputStream();
int byt = -1;
while ((byt = in.read()) != -1) {
byteStr.write(byt);
}
byte[] byteArr = byteStr.toByteArray();
return defineClass(null, byteArr, 0, byteArr.length);

} catch (final RuntimeException rex) {
throw rex;
} catch (final Exception ex) {
ex.printStackTrace();
throw new ClassNotFoundException(fileName);
} finally {
if (in != null) {
try {
in.close();
} catch (final IOException ioe) {
ioe.printStackTrace();
}
}
}
}
}
//end of ClassFileLoader.java
thanks again,
fu bo
"Raymond DeCampo" <rd******@twcny.rr.com> wrote in message
news:gP******************@twister.nyroc.rr.com...
Fu Bo,

OK, I broke down and did it, just to make sure it could be done. The
code is really raw and needs to be cleaned up greatly, but I'll leave
that to you.

Here's the output (you'll have to adjust to Windows, I'm on Linux):

$ java -cp . LoadClassFromFile tmp/HelloWorld.class
Hello World!
$

Real exciting huh? I'll leave the HelloWorld class as an exercise, but
here's the LoadClassFromFile class:

////// BEGIN LoadClassFromFile.java
import java.io.*;
import java.lang.reflect.*;

public class LoadClassFromFile
{
public static void main(String[] args) throws Exception
{
for (int i = 0; i < args.length; i++)
{
Class klass = loadClass(args[i]);
Method main = klass.getMethod("main", new Class[]
{String[].class});
main.invoke(null, new Object[] {new String[0]});
}
}

private static Class loadClass(final String filename) throws
ClassNotFoundException
{
ClassLoader loader = new ClassLoader()
{
protected Class findClass(String name) throws
ClassNotFoundException
{
// Always load the file
InputStream in = null;
try
{
in = new BufferedInputStream(new
FileInputStream(filename));
ByteArrayOutputStream byteStr = new
ByteArrayOutputStream();
int byt = -1;
while ((byt = in.read()) != -1)
{
byteStr.write(byt);
}
byte byteArr[] = byteStr.toByteArray();
return defineClass(null, byteArr, 0, byteArr.length);
}
catch (final RuntimeException rex)
{
throw rex;
}
catch (final Exception ex)
{
ex.printStackTrace();
throw new ClassNotFoundException(name);
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (final IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
};
return loader.loadClass("garbage");
}
}
///// END LoadClassFromFile.java

Again, this code needs a lot of work, but it should give you the basic idea.
Ray

Jul 17 '05 #8

P: n/a
Fu Bo Xia wrote:
thanks ray, this baby works like a charm : )
i used your codes to write a customer implementation of ClassLoader:

No problem, I'll be on contact concerning the licensing.



Just kidding :)

Ray

Jul 17 '05 #9

This discussion thread is closed

Replies have been disabled for this discussion.