473,749 Members | 2,402 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

absolute .class file name to java class name

the java.lang.Objec t.forName method takes a java class name and returns a
Class object associated with that class.
eg. Class myClass = Object.forName( "java.lang.Stri ng");

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 10848
Fu Bo Xia wrote:
the java.lang.Objec t.forName method takes a java class name and returns a
Class object associated with that class.
eg. Class myClass = Object.forName( "java.lang.Stri ng");

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\x xx\MyClass.clas s, 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.Class Loader 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.refec t 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\x xx\MyClass.clas s, 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.Class Loader APIs.

HTH,
Ray

Jul 17 '05 #3
On Mon, 1 Sep 2003 12:07:09 +1000, "Fu Bo Xia" <fu****@optusho me.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\myAp p.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.refec t 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\x xx\MyClass.clas s, 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.Class Loader 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.getPrope rty("java.class .path").toStrin g();
System.setPrope rty("java.class .path", (currentCP + ";" +
"C:\\myJava "));
//set system property java.library.pa th
String currentLP =
System.getPrope rty("java.libra ry.path").toStr ing();
System.setPrope rty("java.libra ry.path", (currentLP + ";" +
"C:\\myJava "));
//set system property java.ext.dirs
String currentED = System.getPrope rty("java.ext.d irs").toString( );
System.setPrope rty("java.ext.d irs", (currentED + ";" +
"C:\\myJava "));

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

fu bo

"Neomorph" <ne******@nospa m.demon.co.uk> wrote in message
news:j4******** *************** *********@4ax.c om...
On Mon, 1 Sep 2003 12:07:09 +1000, "Fu Bo Xia" <fu****@optusho me.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****@optusho me.com.au>
two-finger typed:
i've tried the following for creating a java.lang.Class object for
c:\myJava\myAp p.class

//set system property java.class.path
String currentCP = System.getPrope rty("java.class .path").toStrin g();
System.setPrope rty("java.class .path", (currentCP + ";" +
"C:\\myJava")) ;
Change the ";" into File.pathSepara tor to keep it cross-platform.
//set system property java.library.pa th
String currentLP =
System.getProp erty("java.libr ary.path").toSt ring();
System.setPrope rty("java.libra ry.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.getPrope rty("java.ext.d irs").toString( );
System.setPrope rty("java.ext.d irs", (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 ClassNotFoundEx ception
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.Class Loader 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******@nospa m.demon.co.uk> wrote in message
news:j4******* *************** **********@4ax. com...
On Mon, 1 Sep 2003 12:07:09 +1000, "Fu Bo Xia" <fu****@optusho me.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 . LoadClassFromFi le tmp/HelloWorld.clas s
Hello World!
$

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

////// BEGIN LoadClassFromFi le.java
import java.io.*;
import java.lang.refle ct.*;

public class LoadClassFromFi le
{
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(nul l, new Object[] {new String[0]});
}
}

private static Class loadClass(final String filename) throws
ClassNotFoundEx ception
{
ClassLoader loader = new ClassLoader()
{
protected Class findClass(Strin g name) throws
ClassNotFoundEx ception
{
// Always load the file
InputStream in = null;
try
{
in = new BufferedInputSt ream(new
FileInputStream (filename));
ByteArrayOutput Stream byteStr = new
ByteArrayOutput Stream();
int byt = -1;
while ((byt = in.read()) != -1)
{
byteStr.write(b yt);
}
byte byteArr[] = byteStr.toByteA rray();
return defineClass(nul l, byteArr, 0, byteArr.length) ;
}
catch (final RuntimeExceptio n rex)
{
throw rex;
}
catch (final Exception ex)
{
ex.printStackTr ace();
throw new ClassNotFoundEx ception(name);
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (final IOException ioe)
{
ioe.printStackT race();
}
}
}
}
};
return loader.loadClas s("garbage");
}
}
///// END LoadClassFromFi le.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.refle ct.*;

/**
* A custom implementation of ClassLoader that loads class by it's file
name.
*
* use the loadClass(Strin g 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((a rgs[i]));
System.out.prin t(klass.getName ());
}
} else {
System.out.prin tln(Usage);
}
}

/**
* original code by Raymond DeCampo <rd******@twcny .rr.com>
*/
protected Class findClass(Strin g fileName) throws ClassNotFoundEx ception {

// Always load the file
InputStream in = null;
try {
in = new BufferedInputSt ream(new FileInputStream (fileName));
ByteArrayOutput Stream byteStr = new ByteArrayOutput Stream();
int byt = -1;
while ((byt = in.read()) != -1) {
byteStr.write(b yt);
}
byte[] byteArr = byteStr.toByteA rray();
return defineClass(nul l, byteArr, 0, byteArr.length) ;

} catch (final RuntimeExceptio n rex) {
throw rex;
} catch (final Exception ex) {
ex.printStackTr ace();
throw new ClassNotFoundEx ception(fileNam e);
} finally {
if (in != null) {
try {
in.close();
} catch (final IOException ioe) {
ioe.printStackT race();
}
}
}
}
}
//end of ClassFileLoader .java
thanks again,
fu bo
"Raymond DeCampo" <rd******@twcny .rr.com> wrote in message
news:gP******** **********@twis ter.nyroc.rr.co m...
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 . LoadClassFromFi le tmp/HelloWorld.clas s
Hello World!
$

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

////// BEGIN LoadClassFromFi le.java
import java.io.*;
import java.lang.refle ct.*;

public class LoadClassFromFi le
{
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(nul l, new Object[] {new String[0]});
}
}

private static Class loadClass(final String filename) throws
ClassNotFoundEx ception
{
ClassLoader loader = new ClassLoader()
{
protected Class findClass(Strin g name) throws
ClassNotFoundEx ception
{
// Always load the file
InputStream in = null;
try
{
in = new BufferedInputSt ream(new
FileInputStream (filename));
ByteArrayOutput Stream byteStr = new
ByteArrayOutput Stream();
int byt = -1;
while ((byt = in.read()) != -1)
{
byteStr.write(b yt);
}
byte byteArr[] = byteStr.toByteA rray();
return defineClass(nul l, byteArr, 0, byteArr.length) ;
}
catch (final RuntimeExceptio n rex)
{
throw rex;
}
catch (final Exception ex)
{
ex.printStackTr ace();
throw new ClassNotFoundEx ception(name);
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (final IOException ioe)
{
ioe.printStackT race();
}
}
}
}
};
return loader.loadClas s("garbage");
}
}
///// END LoadClassFromFi le.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
12368
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 the file myclass.class? Will this work if it's run from a relative path, like: java ../progs/myclass
2
2113
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 code for the transformer or in the xsl-template? Where can I find information about this? Your help is very much appreciated,
3
2665
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 <Server>\Netscape\Server4\bin\https\jar folder. But I am not sure whether it is the right location to put the class file. Also I would like to know how to put the class file in jar format. The Java file and the ssjs file code given below. Java part package pdfbase;
1
4544
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 these steps: 1. Write the java class, compile and make a jar (see below for source). 2. Call SQLJ.REPLACE_JAR ('file:/home/pws01ta/pws01ta1/examples.jar','test',0) 3. call sqlj.refresh_classes() 4. Create the function by running "create function...
2
3836
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 there is any C++ class for extracting those structure information from a .class file . I am NOT speaking about decompiling the java class. I just want to parse and extract some information from the .class file.
0
2605
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 with a XML file. I want to be able to save the form automatically for the User so as to prevent typing errors i.e. c:/erikaTemp/subFolder/erika_12345.pdf but from what I've seen this can only be done via the the 'File download' pop up which only...
1
5994
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 getting the Java code to work. I need assistance to get this Double Metaphone Java UDF to work pretty quickly. Here is what I tried to run and the error message that resulted: SQL select nm_frst, NM_LST,...
13
2381
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 find the given path thank You
0
2577
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 Compiler.But now i am facing 1 more problem.i want to run that java class in IntelliJIdea.but its runnig with no error and not getting the out put.This is the converted java class for printing "HelloWorld". import org.mozilla.javascript.*; import...
0
9568
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9389
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8257
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4709
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3320
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2794
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2218
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.