472,782 Members | 1,305 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,782 software developers and data experts.

absolute .class file name to java class name

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
8 10718
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Hal Vaughan | last post by:
I want to have a config file for my program, which means I need to know where the config file is. If I type: java myclass and it runs myclass.class, is there any way to obtain the location of...
2
by: Petterson Mikael | last post by:
Hi, I have one xml file with many class elements. For each class element I need to generate a new new java file.As it is now I get ( my output ) all classes in one file. Do I control this in the...
3
by: Rajesh | last post by:
Hi, I am using iplanet webserver 4.1. I want to call a java class from ssjs file. But I am not getting the result. I have created a java class file and put it in the folder...
1
by: skchonghk | last post by:
Dear all smart experts, I write a simple Java UDF, which should run on DB2 v8 on AIX. But it can't load the Java class. Help ugently needed!! Thanks! I develop and deploy the Java UDF with...
2
by: wolverine | last post by:
Hi, I recently read that every java .class file, is written in a specific binary format. http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html I just want to know whether...
0
by: ErikaW | last post by:
Hi all, I've tried to google this but could not find a clear solution. I have a Web application developed in JDevloper using mostly html and Javascript. I have a pre-defined PDF form which I merge...
1
by: okonita | last post by:
Hello all, I have a Java problem that I hope can be answered here. Very new to DB2 UDB and UDF (we are on DB2v9.5, Linux and Windows), I have managed to get the UDF registered but having problem...
13
oll3i
by: oll3i | last post by:
How do i make a .class file read itself ? i need to display its code from .class file (not .java file) when i try ti simply read the file compiler says it can not find the file or that it can not...
0
by: tosreejithp | last post by:
Hi, My first problem was i am not able to compiled a file from java script to java class.Now its clear and working fine..now i can convert a java script file to java class by Rhino Java Script...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.