473,624 Members | 2,150 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can i unload class in Java

2 New Member
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.Buffere dWriter;
import java.io.FileWri ter;
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("OneBea ns");
out = new BufferedWriter( new FileWriter(o.ge tSrcFile("NewBe an")));
out.write("publ ic 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.prin tln(\"otherPrin t()\");\n");
out.write(" }\n");
out.write("\n") ;
out.write(" public void print() {\n");
out.write(" System.out.prin tln(\"NewBean exist!\");\n");
out.write(" }\n");
out.write("}\n" );
out.close();
a = o.newInstance(" NewBean");
a.print();
System.out.prin tln(a.invoke("g etPropString")) ;
System.out.prin tln(a.invoke("g etPropInteger") );
a.invoke("other Print");
a = null;

o.loadClassLoad er();
srcf = o.getSrcFile("N ewBean");
binf = o.getBinFile("N ewBean");
System.out.prin tln("delete " + srcf + " = " + (((new File(srcf)).del ete()) ? "Yes" : "No"));
System.out.prin tln("delete " + binf + " = " + (((new File(binf)).del ete()) ? "Yes" : "No"));

out = new BufferedWriter( new FileWriter(o.ge tSrcFile("NewBe an")));
out.write("publ ic 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.prin tln(\"otherPrin t()\");\n");
out.write(" }\n");
out.write("\n") ;
out.write(" public void print() {\n");
out.write(" System.out.prin tln(\"NewBean 2 exist!\");\n");
out.write(" }\n");
out.write("}\n" );
out.close();
a = o.newInstance(" NewBean");
a.print();
System.out.prin tln(a.invoke("g etPropString")) ;
System.out.prin tln(a.invoke("g etPropInteger") );
a.invoke("other Print");
a = null;

} catch (Exception e) {
e.printStackTra ce();
}
}
}


*************** ******* File OneBeans.java
import java.lang.refle ct.*;

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

public Object invoke(String methodName, Object[] args)
throws NoSuchMethodExc eption, IllegalAccessEx ception,
InvocationTarge tException, ClassNotFoundEx ception {
Class[] c = {};
return this.getClass() .getMethod(meth odName, c).invoke(this, args);
}

public Object invoke(String methodName)
throws NoSuchMethodExc eption, IllegalAccessEx ception,
InvocationTarge tException, ClassNotFoundEx ception {
Object[] args = {};
return invoke(methodNa me, args);
}
}




*************** ******** File Factory.java
import java.util.HashM ap;
import java.io.PrintWr iter;
import java.io.StringW riter;
import java.io.File;

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

public Factory(String abstractClassNa me) throws ClassNotFoundEx ception {
this.abstractCl assName = abstractClassNa me;
this.packageNam e = "";
int lio = abstractClassNa me.lastIndexOf( ".") + 1;

if (lio > 0) {
this.abstractCl assName = abstractClassNa me.substring(li o);
this.packageNam e = abstractClassNa me.substring(0, lio);
}

this.loadClassL oader();
}

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

private String getFileName(Str ing className, boolean src) {
String propName = (src) ? "sources.pa th" : "bin.path";
String response = (src) ? "java" : "class";
String packPath = this.getPackage Name().replace( ".","/");
return System.getPrope rty(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.lastModifi ed() != bin.lastModifie d()) {
System.out.prin tln("Compiling " + srcFile + "...");
StringWriter err = new StringWriter();
PrintWriter errPrinter = new PrintWriter(err );
String args[] = {"-classpath",
System.getPrope rty("java.class .path"),
"-d",
System.getPrope rty("bin.path") ,
"-sourcepath",
System.getPrope rty("sources.pa th"),
srcFile};
resultCode = com.sun.tools.j avac.Main.compi le(args, errPrinter);
errPrinter.clos e();
result = err.toString();
bin.setLastModi fied(src.lastMo dified());
}

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

public String getSrcFile(Stri ng className) {
return getFileName(cla ssName, true);
}

public String getBinFile(Stri ng className) {
return getFileName(cla ssName, false);
}

public String getPackageName( ) {
return this.packageNam e;
}

public String getAbstractClas sName() {
return this.abstractCl assName;
}

public String getFullAbstract ClassName() {
return this.packageNam e + this.abstractCl assName;
}

public String getFullClassNam e(String className) {
return this.packageNam e + className;
}

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

public OneBeans newInstance(Str ing className)
throws ClassNotFoundEx ception, InstantiationEx ception, IllegalAccessEx ception {
return (OneBeans) this.loadClass( className).newI nstance();
}

public void loadClassLoader () throws ClassNotFoundEx ception {
clearAllClasses ();
allClasses = null;
this.classLoade r = null;
abstractClass = null;
Runtime.getRunt ime().gc();
Runtime.getRunt ime().gc();
allClasses = new HashMap();
this.classLoade r = new MyClassLoader() ;
abstractClass = this.classLoade r.loadOneClass( this.getFullAbs tractClassName( ), true);
}

public Class loadClass(Strin g className) throws ClassNotFoundEx ception {

if (allClasses.con tainsKey(classN ame)) {
return getOneClass(cla ssName);
} else {
String result = compile(this.ge tSrcFile(classN ame), this.getBinFile (className));

if (result == null) {
Class cl = this.classLoade r.loadOneClass( this.getFullCla ssName(classNam e), true);
allClasses.put( className, cl);
return cl;
} else {
System.err.prin tln(result);
return null;
}
}
}
}

class MyClassLoader extends ClassLoader {

public Class loadOneClass(St ring className, boolean resolve) throws ClassNotFoundEx ception {
return this.loadClass( className, resolve);
}

}
Nov 23 '07 #1
2 2958
inetjack
2 New Member
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 Recognized Expert MVP
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
7233
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 circumstances - kind of webstart, but dynamic (you have to restart webstart to get a new version of an application) and without a GUI. The problem is that I have some singletons among my objects. Turns out that garbage collector has some trouble...
2
10842
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. When trying to delete the DLL file I get an exception that access is denied. When trying to copy over the DLL file, I get an exception that it is being used by another process.
2
4341
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 Assemblies into a seperate AppDomain and closing it when finish, which would suit me fine. However, I have been able to find an example.
6
8190
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 this 5 line program: AppDomain domain = AppDomain.CreateDomain("MyDomain"); domain.CreateInstance("TempDLL", "TempDLL.Class1"); MessageBox.Show("try deleting file now"); //cant delete file AppDomain.Unload(domain);
2
6865
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 without interfaces if need be. But try as I may they will ot unload. I have been working on this problem for weeks. I have seen other apps using Remoting but I know there has got to be a way to create a child AppDomain and reference obkect via...
6
4719
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 existing user control and load the newly selected one is pretty bulky. Every time we add a new user control to the project, we have to add some code in the section where we are loading/unloading. Is there a more dynamic, more efficient way to...
3
2604
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 load AppDomain. B monitors disk to see if some files chang. If some file changes, B will try to unload the AppDomain it loaded before.
2
5253
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
1746
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 will not working properly how can solve this issue.
0
8236
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8679
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
8621
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
8335
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
8475
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6110
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
2606
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
1
1785
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1482
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.