Using Reflection on classes outside the classpath
Hi all,
Im writing a tool that takes a directory containing class files (from other internal projects) and returns information such as the Class name, package, parent, constructors and public methods. These projects will not be on the classpath and will also use jars that are not on the classpath.
I decided that ClassLoaders were the way to go. So I created a SimpleClassLoader class that takes a file, reads it in as an array of bytes and calls defineClass:
public class SimpleClassLoader extends ClassLoader
public SimpleClassLoader()
public synchronized Class loadClass(String name, boolean resolveIt) throws ClassNotFoundException
System.out.println("1) loading class: " + name);
return super.loadClass(name, resolveIt);
public synchronized Class loadClass(File classFile) throws ClassNotFoundException
System.out.println("2) Loading class: " + classFile.getName());
try
byte[] data = getClassData(classFile);
return defineClass(name, data, 0, data.length);
catch (IOException e)
throw new ClassNotFoundException();
byte[] getClassData(File classFile) throws IOException
byte result[];
try
FileInputStream in = new FileInputStream(classFile);
result = new byte[in.available()];
in.read(result);
in.close();
return result;
catch (IOException e)
throw new IOException();
public class ClassParser
public Class parse (File classFile)
SimpleClassLoader loader = new SimpleClassLoader();
Class reflectClass = null;
try {
return loader.loadClass(classFile);
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading class: " + classFile.getName() + "\n" + cnfe);
return null;
}This worked for simple classes but when the superclass was in a jar or another file in the directory that hadnt already been loaded a ClassNotFoundException was thrown. So I then decided to try using URLClassLoader and loading in the jars and the entire source directory before calling findClass on it.
class MyURLClassLoader extends URLClassLoader
public MyURLClassLoader(URL[] urls)
super(urls);
public Class findClass(String classname) throws ClassNotFoundException
return super.findClass(classname);
public class ClassParser {
private URL[] _classpath;
private String _root;
public ClassParser(File[] files, String root) {
_root = root;
_classpath = new URL[files.length];
for (int i = 0; i < files.length; i++) {
try {
URL url = new URL("jar", "", files.toURL() + "!/");
this._classpath[i] = url;
} catch (MalformedURLException e) {
e.printStackTrace();
public Class parse (File classFile) {
MyURLClassLoader urlLoader = new MyURLClassLoader(_classpath);
Class reflectClass = null;
String classname = "";
// Try to load a Class instance from the file
try {
classname = getClassName(classFile);
return urlLoader.findClass(classname);
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading class: " + classname + "\n" + cnfe);
return null;
String getClassName (File file) throws ClassNotFoundException {
if (file.getAbsolutePath().startsWith(_root)) {
String packagePath = file.getAbsolutePath().substring(_root.length(), file.getAbsolutePath().lastIndexOf("."));
packagePath = packagePath.replace(File.separatorChar, '.');
return packagePath;
} else {
throw new ClassNotFoundException();
public static void main(String args[]) {
File [] files = new File [] {
new File("C:\\Projects\\app\lib\\jacob-1.6.jar"),
new File("C:\\Projects\\app\\lib\\xalan.jar"),
new File("C:\\Projects\\app\\lib\\xmlunit1.0.jar"),
new File("C:\\Projects\\app\\classes\\com\\foo\\bar\\swing\\")
parser = new ClassParser(files, "C:\\Projects\\app\\classes\\");
This seems to work when I call findClass on a class thats in one of the jars but not on a class in the classes directory.
Does anyone have any ideas what im doing wrong or whether im barking up the wrong tree completely??
Thanks,
Conor
The URLs that you supply to an URLClassLoader each define the location of the default package for that portion of the classpath for the ClassLoader.
This is the problem line
new File("C:\\Projects\\app\\classes\\com\\foo\\bar\\swing\\")I suspect that it should be..
new File( "C:\\Projects\\app\classes" )as this is the location of that default package.
Similar Messages
-
Class file is referencing a type outside the classpath???
Hi All,
I'm developing a EJB project in NWDS.
I'm getthing the below syntax error.
This compilation unit indirectly references the missing type com.sap.exception.BaseException (typically some required class file is referencing a type outside the classpath)
Can you please help me to resolve this?
Thanks in advance.
SundarHi Sundar,
You need to add the ejb20.jar file to your Project classpath.
If you are developing the project locally then the jar file can be directly added to the class path using the Project Properties --> Java build PAth --> Libraries tab --> Add External Jar.
If it is a DC development, the ejb20.jar can be found under the SAP-JEE software component of your track.
Hope it helps.
Regards,
Alka. -
JARs in WEB-INF/classes on the classpath? [NEWBIE]
Hello,
I am under the impression that any files (including JARs and all within
them) are on the classpath if they are in the folder WEB-INF/classes.
I have a WAR file that contains a JAR file that in the WEB-INF/classes
folder. The JAR file contains a class under the package structure
"mvc.users.Members". I know its there as I checked the WAR file structure
before deploying.
In the WAR file I have a Struts RegisterAction class in the package/folder
"mvc.registration.RegisterAction" which has the following code to create a
Member object:
Member member = new Member();The Member class is imported into RegisterAction using
import mvc.users.Members;and JBuilder appears to recognise Members as on the classpath and compiles
with no errors.
My problem is after I have deployed the WAR file, submitting a form to the
RegisterAction gets the error below:
javax.servlet.ServletException: Servlet execution threw an exception:
root cause:
java.lang.NoClassDefFoundError: mvc/users/Member
mvc.registration.RegisterAction.execute(RegisterAction.java:22)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)If the class "mvc.users.Member" is in the JAR file in the WEB-INF/classes
folder and the "mvc.registration.RegisterAction" class in the WAR file
does (according to JBuilder) see the "mvc.users.Member" class on the
classpath and compiles... why then do I get this error?
Thanks for your help.
A Desperate Newbie,
MarkI answered this in the JSP forum - you need to put JAR files in WEB-INF/lib.
-
Revision: 5140
Author: [email protected]
Date: 2009-03-02 12:09:24 -0800 (Mon, 02 Mar 2009)
Log Message:
Removing [ExcludeClass] from classes outside the package.
QE Notes: None.
Doc Notes: None.
tests: checkintests
Modified Paths:
flex/sdk/trunk/frameworks/projects/flex4/src/mx/layout/HorizontalLayout.as
flex/sdk/trunk/frameworks/projects/flex4/src/mx/layout/VerticalLayout.as -
How to use Landmark in a Class outside the Parsley Context
Hi all,
Is there anyway to get the Landmark metadata work without adding the annotated Class in the Parsley Context file?
I mean, I have a Class such as:
[Landmark(name="content.foo")]
public class MyClass extends ManagedClass {
[Enter(time="every")]
public function enter():void
LOG.info("content.foo:Enter");
Problem:
Enter method is never fired although ManagedClass( the super class ) has a <parsley:Configure /> tag ( and, of course, all injections happen ).
Adding MyClass to the Parsley Context file makes everything work but is there anyway to make this Landmark work without doing that?
Thanks.That's more of a Parsley question than C3 and AFAIK it's not feasable. The other way around is with i.e. the ProcessSuperclass object definition in Parsley. Check out Parsley's developer manual on that (chapter 3 should explain this)
-
How to refer to a protected class outside the enclosing package
Hi all,
At the page 357 of the book Java Language Specification(Second Edition), when saying about checking accessibility of Type and Method, they concern Let C be the class containing the method invovation T.m, if T is in a different package than C, and T is protected then T is accessible if and only if C is a subclass of T. I just wonder how to refer a protected type outside the package it declared.
For example,
package test;
public class test {
static protected class protectedTest {
public void foo() {..}
in another package
import test.*;
class subtest extends test.protectedTest { <- error
Anyone can give me an example showing an invocation directly to foo() declared in class test.protectedTest ? The invocation should appear outside package test.
Thanks,
Ha ChauThe protected inner class would be accesible only within a class which extends test, where you could either use or extend it as in:
class subtest extends test {
private static class sub2 extends protectedTest {
} -
How to compile package which contain class outside the package
I am writing a JDBC driver.
I have the following package structure in the folder:
MyDriver
|_manager.jar
|_com
|_ jdbc
|_ HXDriver
|_ HXConnection
|_ HXResultSet
|_ HXStatementIn manager.jar, there is a remote object Interaface(Manager.java) which I need to use inside HXConnection.
My question is how to compile(or/and how to set the classpath)so that I can compile the 4 classes inside jdbc package.
I tried this:
C:\MyDriver>javac -cp .;manager.jar com/hx/jdbc/*.java
However, this does not work, compiler says it cannot find Manager
Please help me.
CheersD:\380 Project\Driver>javac -cp .;manager.jar com\hx\jdbc\*.java
com\hx\jdbc\HXConnection.java:21: cannot find symbol
symbol : class Manager
location: class com.hx.jdbc.HXConnection
private Manager manager;
^
com\hx\jdbc\HXStatement.java:18: cannot find symbol
symbol : class Manager
location: class com.hx.jdbc.HXStatement
private Manager manager;
^
com\hx\jdbc\HXStatement.java:20: cannot find symbol
symbol : class Manager
location: class com.hx.jdbc.HXStatement
public HXStatement(Manager manager){
^
com\hx\jdbc\HXConnection.java:41: cannot find symbol
symbol : class Manager
location: class com.hx.jdbc.HXConnection
manager = (Manager)reg.lookup("manager");
^ -
How to create an instance of a protected class outside the enclosing packag
Hi all,
I have a piece of code like this:
package test;
public class A {
protected class B { }
How to create an instance of B outside the package test ? Could you please give me an example ?
Thanks
Ha ChauThank WirajR for your reply, but in your solution,
you have to create an instance of B inside class A
and pass it outside. I would like to know whetherwe
can create an instance of class B outside thepackage
test. That means I want the instance creation
expression of B appears outside the package test.Can
we do that?
If you want to use a class this way then it shouldn't
be marked protected. I can't see why you don't
just declare it public if that's what it is.
Wouldn't be much point to haveing a protected
modifier if it had no effect, would there?I think there is use for it if you use an interface to filter out the parts you want to give public access to, and keep the part you want to keep protected, protected -
Can We Use Multiple Edgehero Classes On The Same Element?
Does anyone know if it is possible to add multiple Edgehero classes to the same element? More specifically, I would like to use RotateX and RotateY on a rectangle, but it only seems to do one or the other, adding both classes to the element doesn't make it rotate in both directions.
Maybe check out the Star Wars demo to see if that would help.
Rob got the idea from the one I made earlier and here is the code:
sym.$('gradient').css('background', '-moz-linear-gradient(top, rgba(0,0,0,1) 0%, transparent 100%)');
sym.$('container').css('-moz-transform-origin', '50% 100%');
sym.$('container').css('-moz-transform', 'perspective(250px) rotateX(25deg)');
// Chrome and others
sym.$('gradient').css('background', '-webkit-linear-gradient(top, rgba(0,0,0,1) 0%, transparent 100%)');
sym.$('container').css('-webkit-transform-origin', '50% 100%');
sym.$('container').css('-webkit-transform', 'perspective(250px) rotateX(25deg)');
// Internet Explorer
sym.$('gradient').css('background', '-ms-linear-gradient(top, rgba(0,0,0,1) 0%, transparent 100%)');
sym.$('container').css('-ms-transform-origin', '50% 100%');
sym.$('container').css('-ms-transform', 'perspective(250px) rotateX(25deg)');
and the orginal file before edgeHero;
https://app.box.com/s/068vx5x6lj5t2yydrx17 -
Can you use two tax classes in the same payroll run?
Hi,
I have a wage type that is currently set to Tax Class 1 (fully taxed) for processing class 71, I need to change it to tax class 7 (Withholding and SUI only) and have it computed as part of the regular payroll run and also by itself using offcycle.
When I have it set as Tax Class 1, all is well, when I change it to tax class 7, I get the error...
BSI Messages and Status 4101 CAN NOT PROCESS DUPLICATE RESIDENT STATE FED
This is the first time we're using this tax class and I think i have it set up correctly in the tax model but am not for sure.
Any suggestions? I'd really appreciate some guidance as I've looked
Thanks!
Stephanie AbrahamsonI think you should not change the PRCL 71 from 1 to 7 wide open. Start it with begin date of pay period you want and keep the history with PRCL 71 1.
As well check the config of tax model.
Arti -
Accessing a class outside the package
Hi friends !
Suppose I have a class called InsidePackageClass which is placed under C:\Package and other called OutsidePackageClass that is placed directly under C:
Suppose my classpath points to C:\ and I want to declare a OutsidePackageClass member variable in the class InsidePackageClass. This leads me to an error. The compiler complains that it can't find the OutsidePackageClass class.
What's wrong ?
C:\
|-Package
| |---------InsidePackageClass
|-OutsidePackageClass
Thanks in advance
CleversonLike this?
File: C:\OutsidePackageClass.java
[code]class OutsidePackageClass {
static String attribute = "first";
public OutsidePackageClass() {
}[/code]
File: C:\Package\InsidePackageClass.java
[code]class InsidePackageClass {
public InsidePackageClass() {
OutsidePackageClass o;
}[/code]
To compileset CLASSPATH=C:\
cd \Package
javac ../OutsidePackageClass.java
javac InsidePackageClass.javaNote, javac will not run with current directory C:\ -
How to load a class from a jar not in the classpath
I have a gazillion jars of class files that I want to access dynamically in an application. I don't want to list every jar. The jars also contain images. With images you can explicitly point to the jar with and load the image with createImage....
"jar:file:/C:/myjarlocation/myjar.jar!/pathtoimage/image.gif"
Is there a similar string you can use when creating classes on the fly in a classloader with getClass().forName("classname") ??Hm, if you are not in an EJB container or some other environment that won't let you create a classloader, you might create a new URLClassLoader with a path pointing to those JARs. You will probably want to use your normal application class loader as the parent loader, so any referenced common class definitions are found during the load.
Note that - in order to make use of the classes - you will normally need to know that they implement some interface (or inherit from a common base class) to which you can cast their instances. These Interfaces/base classes will have to be packaged for normal loading by your application class loader; else the cast will trigger an error during compile time. After this, loading them dynamically during runtime is no longer an option since they are referenced directly in the sourcecode.
Alternatively you might do away with interfaces/base classes and call methods of dynamically loaded classes also dynamically: via reflection. But I guess this is too cumbersome for what you might have in mind. Also it has more invocation overhead, less type safety and handling all these exceptions wrapped in InvocationTargetExceptions can quickly become a nightmare too... -
Using reflection on passed classes
Hello,
I have been trying to write a common function to return the variables and values of a class passed into it. The function uses reflection to iterate through the Fields and returns a string of the variables and values. Is it anything to do with scope, as the same code works when I paste the method into the class I am looking at (See below)?
I have pasted the code fragments below.
Thanks
stuart
* Returns XML fragment of name value pairs of member/value
* @param iClass the class under inspection
* @return XML fragment of name value pairs of member/value
public static String inspectMemberVariables(Class iClass)
String oStr = new String();
try
Class c = iClass.getClass();
Field[] f = c.getFields();
System.out.println(f.length);
for (int i=0; i < f.length; i++)
// identify the field
Field fld = c.getField( f.getName());
//get the field name and grab the field value from the class
oStr += f.getName()
+ "=\""
+ fld.get(c)
+ "\" ";
} // for (int i=0; i < f.length; i++)
oStr = "classname=\""
+ c.getName()
+ "\" "
+ oStr;
} //end of try
catch (NoSuchFieldException e)
System.out.println(e);
catch (SecurityException e)
System.out.println(e);
catch (IllegalAccessException e)
System.out.println(e);
} //end of catch
return oStr;
} // end ofinspectMemberVariables
Where the code is called:
public class ReflectionTest extends PPSpposEBCore
public String strg;
public ReflectionTest()
String str2 = new String ();
str2 = ClassProperties.inspectMemberVariables(this.getClass());
System.out.println(str2);
public static void main(String[] args)
String str = new String ();
try
ReflectionTest rt = new ReflectionTest();
// set dummy values to test
rt.mPossessionId = 12;
rt.mBusinessPossRef = "look it works";
rt.mCreatedTs = new Date();
//ClassProperties cp = new ClassProperties();
//str2 = ClassProperties.inspectMemberVariables(rt.getClass());
Class c = rt.getClass() ;
Field[] f = c.getFields();
System.out.println(f.length);
for (int i=0; i < f.length; i++)
// identify the field
Field fld = c.getField( f.getName());
//grab the field name and field value from the class
str += f.getName()
+ "=\""
+ fld.get(rt)
+ "\" ";
} // for (int i=0; i < f.length; i++)
str = "classname=\""
+ c.getName()
+ "\" "
+ str;
System.out.println(str);
} //try
catch (NoSuchFieldException e)
System.out.println(e);
catch (SecurityException e)
System.out.println(e);
catch (IllegalAccessException e)
System.out.println(e);sorry it doesn't work, interface cannot have method body, i didn't know it. You couldn't access to private and protected datas with an exterior method. You can make a package with classes you want to inspect and a class who inspect. The classes of a package can access to protected datas.
-
Using reflection...
Hi,
I have one class. to run that, I am calling like the following...
java -classpath ;.;\comdotebo; com.pack1.MyClass
now I want to take the reference of this class(dynamically) using reflection pakcage like the following...
Class cla = Class.forName("com.pack1.MyClass");
but to take the class reference I need to set the classpath;
so how can i set the classpath dynamically.
please give proper solution
thanks
Raja Ramesh Kumar Mhere the case is we know both the class and the class path at run time only
for ex: see the following.....
I have two files .....
1) c:\dir1\com\pack1\MyClass1.class
2) c:\dir2\com\pack2\MyClass2.class
now I want to access both the classes using reflection from ...
c:\dir3\com\pack3\MainClass.class
using reflection, we can write the following...
Class clas1 = Class.forName("com.pack1.MyClass1");
if I am taking like this, then I am getting ClassNotFoundException.
becoz, for that we have to give the proper classpath before running the program.
like.
set classpath=%classpath%;.;c:\dir1;
but my problem is here I know the the class name (for ex: com.pack1.MyClass1) and the classpath (ex: c:\dir1)
at runtime only.
so please tell me how to solve this problem
regards
Raja Ramesh Kumar -
WEB-INF/classes not in classpath issue - bug or specification?
I've noticed BC4J expects some of its configuration files to be present in the standard classpath or the application.
However, when running web-apps, the WEB-INF/classes are used for loading classes by the JVM, but they are not in the classpath literaly which causes BC4J not to find its metadata files - this has caused many people to be confused because they believed (like me) that the /classes folder is just another part of the classpath.
But someone has to solve this! After all, if I have a million web-apps, I (as a BC4J user) do not want to include a million JAR files in the classpath. I want to put the JAR in the classes directory and have BC4J find it automatically since its part of the web-app's classes, jars/zips and such.
The question is, is this a BC4J issue (not finding the files) or a Java Specification issue? and if this is a mere BC4J issue, why won't Oracle provide a small patch for BC4J (simply release an updated JAR/ZIP file)? Or instead, put it in BC4J release notes (unless its already there and I've missed it..) so that customers won't have to spend/waste valuable time trying to understand.
Regards to all,
Arik Kfir.Originally posted by Arik Kfir ([email protected]):
I've noticed BC4J expects some of its configuration files to be present in the standard classpath or the application.
However, when running web-apps, the WEB-INF/classes are used for loading classes by the JVM, but they are not in the classpath literaly which causes BC4J not to find its metadata files - this has caused many people to be confused because they believed (like me) that the /classes folder is just another part of the classpath.
But someone has to solve this! After all, if I have a million web-apps, I (as a BC4J user) do not want to include a million JAR files in the classpath. I want to put the JAR in the classes directory and have BC4J find it automatically since its part of the web-app's classes, jars/zips and such.
===========================================
If I understand you correctly, it sounds like you need to put the bc4j .jar files in the /j2ee/home/lib directory...by placing a jar file there, it becomes available to all web applications running inside OC4J...
does that solve your problem?
regards,
Mike Conway
UNC Chapel Hill
Maybe you are looking for
-
Why is my ipod touch unresponsive (black screen)
i have a ipod touch 1 generation 2.2.1 and it just stoped and now it has a black screen and is unresponsive no battery sign telling me to charge or any thing just a black screen i have it on the charger now can you help me
-
Stuck Outbound Queues in CRM system
Hi Guys, In CRM system the out bound queuse for the Sales Orders got stuck with the following error "Too many recursive subroutine calls" The Sales Orders are not getting replicated from the CRM system to R/3. The business partners associated with th
-
I can't use my iPhone when charging.
I can't use my iPhone when charging.
-
Can a drum pattern created in Ultrabeat be limited to playing only once? Basically creating a single bar.
-
Hi, could not install 9i R2 on SUSE9. Copying process hung when it started to copy JRE. and the copy status says "Link Pending". My error log shows : java.lang.UnsatisfiedLinkError: /tmp/OraInstall2005-07-14_07-5doPost=true