473,322 Members | 1,409 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 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 10791
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.