473,398 Members | 2,212 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,398 software developers and data experts.

Can i unload class in Java

Hi,

This is a little test application, generating and compiling code at runtime.

The loadClassLoader() method of the Factory Object suppose to unload all class previously loaded.

It does not work!!!

Somebody knows why?

Thanks in advance for your help

inetjack



************************** File Test.java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;

public class Test {

public static void main(String[] args) {

try {
Factory o;
BufferedWriter out;
OneBeans a;
String srcf;
String binf;

o = new Factory("OneBeans");
out = new BufferedWriter(new FileWriter(o.getSrcFile("NewBean")));
out.write("public class NewBean extends OneBeans {\n");
out.write(" public NewBean() {\n");
out.write(" }\n");
out.write("\n");
out.write(" public String getPropString() {\n");
out.write(" return \"Hello World\";\n");
out.write(" }\n");
out.write("\n");
out.write(" public Integer getPropInteger() {\n");
out.write(" return 2;\n");
out.write(" }\n");
out.write("\n");
out.write(" public void otherPrint() {\n");
out.write(" System.out.println(\"otherPrint()\");\n");
out.write(" }\n");
out.write("\n");
out.write(" public void print() {\n");
out.write(" System.out.println(\"NewBean exist!\");\n");
out.write(" }\n");
out.write("}\n");
out.close();
a = o.newInstance("NewBean");
a.print();
System.out.println(a.invoke("getPropString"));
System.out.println(a.invoke("getPropInteger"));
a.invoke("otherPrint");
a = null;

o.loadClassLoader();
srcf = o.getSrcFile("NewBean");
binf = o.getBinFile("NewBean");
System.out.println("delete " + srcf + " = " + (((new File(srcf)).delete()) ? "Yes" : "No"));
System.out.println("delete " + binf + " = " + (((new File(binf)).delete()) ? "Yes" : "No"));

out = new BufferedWriter(new FileWriter(o.getSrcFile("NewBean")));
out.write("public class NewBean extends OneBeans {\n");
out.write(" public NewBean() {\n");
out.write(" }\n");
out.write("\n");
out.write(" public String getPropString() {\n");
out.write(" return \"Hello World Again\";\n");
out.write(" }\n");
out.write("\n");
out.write(" public Integer getPropInteger() {\n");
out.write(" return 22;\n");
out.write(" }\n");
out.write("\n");
out.write(" public void otherPrint() {\n");
out.write(" System.out.println(\"otherPrint()\");\n");
out.write(" }\n");
out.write("\n");
out.write(" public void print() {\n");
out.write(" System.out.println(\"NewBean 2 exist!\");\n");
out.write(" }\n");
out.write("}\n");
out.close();
a = o.newInstance("NewBean");
a.print();
System.out.println(a.invoke("getPropString"));
System.out.println(a.invoke("getPropInteger"));
a.invoke("otherPrint");
a = null;

} catch (Exception e) {
e.printStackTrace();
}
}
}


********************** File OneBeans.java
import java.lang.reflect.*;

public abstract class OneBeans {
public abstract void print();

public Object invoke(String methodName, Object[] args)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
Class[] c = {};
return this.getClass().getMethod(methodName, c).invoke(this, args);
}

public Object invoke(String methodName)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {
Object[] args = {};
return invoke(methodName, args);
}
}




*********************** File Factory.java
import java.util.HashMap;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.File;

public class Factory {
private HashMap allClasses;
private String abstractClassName;
private String packageName;
private Class abstractClass;
private MyClassLoader classLoader;

public Factory(String abstractClassName) throws ClassNotFoundException {
this.abstractClassName = abstractClassName;
this.packageName = "";
int lio = abstractClassName.lastIndexOf(".") + 1;

if (lio > 0) {
this.abstractClassName = abstractClassName.substring(lio);
this.packageName = abstractClassName.substring(0, lio);
}

this.loadClassLoader();
}

private void clearAllClasses() {
try {
allClasses.clear();
} catch (Exception e) {
}
}

private String getFileName(String className, boolean src) {
String propName = (src) ? "sources.path" : "bin.path";
String response = (src) ? "java" : "class";
String packPath = this.getPackageName().replace(".","/");
return System.getProperty(propName) + "/" + packPath + className + "." + response;
}

private String compile(String srcFile, String binFile) {
File src = new File(srcFile);
File bin = new File(binFile);
int resultCode = 0;
String result = "";

if (src.lastModified() != bin.lastModified()) {
System.out.println("Compiling " + srcFile + "...");
StringWriter err = new StringWriter();
PrintWriter errPrinter = new PrintWriter(err);
String args[] = {"-classpath",
System.getProperty("java.class.path"),
"-d",
System.getProperty("bin.path"),
"-sourcepath",
System.getProperty("sources.path"),
srcFile};
resultCode = com.sun.tools.javac.Main.compile(args, errPrinter);
errPrinter.close();
result = err.toString();
bin.setLastModified(src.lastModified());
}

return (resultCode == 0) ? null : result;
}

public String getSrcFile(String className) {
return getFileName(className, true);
}

public String getBinFile(String className) {
return getFileName(className, false);
}

public String getPackageName() {
return this.packageName;
}

public String getAbstractClassName() {
return this.abstractClassName;
}

public String getFullAbstractClassName() {
return this.packageName + this.abstractClassName;
}

public String getFullClassName(String className) {
return this.packageName + className;
}

public Class getOneClass(String className) {
return (Class) allClasses.get(className);
}

public OneBeans newInstance(String className)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
return (OneBeans) this.loadClass(className).newInstance();
}

public void loadClassLoader() throws ClassNotFoundException {
clearAllClasses();
allClasses = null;
this.classLoader = null;
abstractClass = null;
Runtime.getRuntime().gc();
Runtime.getRuntime().gc();
allClasses = new HashMap();
this.classLoader = new MyClassLoader();
abstractClass = this.classLoader.loadOneClass(this.getFullAbstract ClassName(), true);
}

public Class loadClass(String className) throws ClassNotFoundException {

if (allClasses.containsKey(className)) {
return getOneClass(className);
} else {
String result = compile(this.getSrcFile(className), this.getBinFile(className));

if (result == null) {
Class cl = this.classLoader.loadOneClass(this.getFullClassNam e(className), true);
allClasses.put(className, cl);
return cl;
} else {
System.err.println(result);
return null;
}
}
}
}

class MyClassLoader extends ClassLoader {

public Class loadOneClass(String className, boolean resolve) throws ClassNotFoundException {
return this.loadClass(className, resolve);
}

}
Nov 23 '07 #1
2 2945
Oupssss

I forgot to tell you, that little application must run with -D<sources path> and -D<binary path> flag on the command line of java.exe

You must have the Tools.jar into the classpath too.

Thanks

inetjack
Nov 23 '07 #2
JosAH
11,448 Expert 8TB
I don't want to spoil your fun but did you have a look at the JavaCompiler
interface? It's quite new and does the compilation part of what you're trying to
accomplish. It's quite new: >= 1.6

Class objects are supposed to be gc'd be default unless you specify a -X flag:
-Xnoclassgc; if you want to get rid of them on demand you have to write your
own class loader (you can conveniently derive for other loaders).

kind regards,

Jos
Nov 23 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Saruman | last post by:
Unfortunately I am not able to find a direct answer to this question neither in documentation nor in newsgroups. I have an application biggest part of which is dynamically reloaded in certain...
2
by: Lauren Hines | last post by:
Hello, I have read numerous post stating that the only way to unload an assembly (DLL in my case) is to create a separate AppDomain, load the assembly, then unload it by calling AppDomain.Unload....
2
by: Sam Martin | last post by:
Morning all, Right, I've read untold articles now, listening to people bitch about there being no Unload method for Assembly. Plenty of people do counter that this is possible by loading the...
6
by: Wal Turner | last post by:
Hi there. There are various snippets on forums regarding issues with AppDomain.Unload and how it just doesnt work. Fortunately, I got it working with the base case, after much fiddling. Consider...
2
by: brianbender | last post by:
I am trying to load and unload assemblies dynamically and call methods and properties when loaded into an Appdomain I can load assemblies all day in the current AppDomain without references and...
6
by: Ronald S. Cook | last post by:
We have a Windows app that has one main form (a shell, sort of). We then load user controls into a panel on the form depending on what the user has selected. Our current code to unload the...
3
by: Tao | last post by:
hi.. group, A wired question about FileSystemWatcher and Unload an AppDomain. I have a class A which creates class B. When B is created, B loads an AppDomain and execute some functions on the...
2
by: TestGames | last post by:
Hi, I need to unload my activex after using it throght my web page(java script). I create it using the new operator. Is there any way or method to make ie unload the file. Thanks, TestGames
1
by: iamnidheesh | last post by:
i want check a condition on body unload(java script)the function is working on first unload time. in my application some times i have to remain in that page itself so on the second time onwards it...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.