Compressing classes and jars using pack200

Dear All,
As per the following I expected standalone pack200.exe and
unpack.exe in J2SDK1.5.0 Beta. But I could not find it.
http://java.sun.com/j2se/1.5.0/docs/guide/deployment/deployment-guide/pack200.html#pack200_compression
Is there any other way to get the standalone above compression tools?
I want to compress my j2re1.4.2 based application jars.
Thanks for ur help.
regards,
MSKumar

If you still need an answer to this question, try one of the forums found under Java Technology at:
http://forum.java.sun.com/index.jsp

Similar Messages

  • Where to put common classes and jar files

    hi,
    i want to put some classes and jar files in a common folder so that it can be accessed by other applications is there any way doing that.In tomcat server they have common and shared directories once any classes are into that folder they are being accessed easily ,but i am having problems with sun one .
    Regards
    Ameem Sami

    Did you find a solution for this? I'm having the same problem.
    Thanks,
    Tony

  • Find Universe, classes and objects used in each report

    I want to find a list of universes, classes and objects used in each report
    or the other way to find list of reports which use a particular universe. please let know, i could not get much information from activity universe in a proper way.

    Hello Venkataramat,
    plese post in more detail what kind of report you are using Crystal report ? webi ? Deski.
    Please post in the specific forums.
    If you have a Crystal Report I recommend to post this query to the [Crystal Reports Design|SAP Crystal Reports; forum.
    Best regards
    Falk

  • Trace all classes and methods used

    I have a java application that uses a third party API jar file. I call methods on classes in this API. I need a application/API that will enable me dyamically (or possibly statically) to determine every single method in every class used that my application uses. If for example, my application uses a method on a class Stock : Stock.lookup("abc") and in turn lookup() calls a method in Stock2 and that method calls a method in Stock3. I need a way to to know the whole list of all methods in classes used for each method in my class.
    Please let me know if you know any such Application/API that does this.
    Ahmed

    The java -verbose:class output was useful, but I need an API/Application that will show me clearly which mehod each mehod invokes and in which class; method by method e.g:
    method foo1(String s) in class ABC.java line 19
    invokes foo2() in class ABC2.java line 3224
    invokes foo3() in class ABC3.java line 1556
    Ahmed

  • I have J2ME application classes and jar at server, but ............

    Hi All,
    My application is such that some J2ME Applications are loaded in a webserver. Upon the request J2ME should show how many applications are available in webserver and what are they.
    Up to this part i am able to do. I can read the .class or .jar file from my webserver. But my doubt is how i can execute that J2ME application at runtime.
    Thanx in Advance.
    Amarnath Revuri

    Hi john wen,
    1)I am using Wireless Tool Kit 1.0.4 on WinNT
    I have downloaded the midp1.0.3 as u suggested and i read the running.html.
    midp -transient <descriptor URL> [<MIDlet name>]
    this above command you have given is used to run the remote MIDlet at command prompt. But my requirements is i have an J2ME MIDlet already running. In that application there is a situation that i need to get remote application(MIDlet/CAnvas/Form/List etc) stored in my existing MIDlet suite and run it without killing my application that is currently running. Can you pls tell me if you have any idea about this.
    2) Can you tell me how i can access/modify/create a text file in my WinNT system where my MIDlet application is running.
    Amarnath Revuri

  • .class and .jar

    Hi every one,
    In a research lab that i'm working, we're developing a big software. Eventually we are trying to make it destributed.
    Our problem is that every time we try to send our updated code to the our clients, we send the library in .jar. Bad thing about .jar is that it can be opened and all .class files can be retrieved which let people see the actual code.
    Is there any solution to not let the poeple see the actuall source code???
    thanx.

    Class files do contain actual bytecode, not just "headers". You can use a decompiler to get a reasonable facsimile to the original Java source code, especially if the Java source was compiled with debugging information.
    In order to make decompilation harder, you can use an obfuscator to mangle some of the names the program uses. To make decompilation impossible, you can encrypt the class files using strong encryption and write a custom classloader that will decrypt the class files.

  • Applets and classes and jars

    ok, this has probably been asked and answered a million times, but I cannot find it anywhere.
    heres my problem:
    I have an applet and am trying to run it from internet explorer and all I get is a blank screen. the code is:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" CONFILTERED="text/html; charset=windows-1252"></meta>
    <title>Segregation of Duties</title>
    <link type="text/css" rel="stylesheet" href="department.css"/>
    <style type="text/css">
    body {
    background-color: #528cff;
    a:link { color: #528cff; }
    <applet code=mypackage.SODApplet.class archive=deploy.SODApplet.jar Height=300 Width=300>
    </applet>
    </style>
    </head>
    <body></body>
    </html>
    Apparently it cannot find the class or the jar. But how do I tell it where to find them?
    The class is in c:/jdevinstall/jdev/mywork/SOD/SODReports/classes/mypackage
    and the jar is in
    c:/jdevinstall/jdev/mywork/SOD/SODReports/deploy/
    the html is on my desktop
    Richard

    Nothing to do with Servlets here... but:
    The Applet JAR has to be in a path relative to the web page, or the server root. You are asking the client (the web browser the user is using) to download the JAR and look inside for the class to run. So the web browser must be able to see that JAR. As such it needs to be in a directory your server hosts. The easiest is to have it in a directory relative to the page that displays it, such as:
    Web Hosted Directory:   C:\Web\HostedDir\
    Web page location                       \MyApp\SODAppletPage.html
    JAR file location                       \MyApp\lib\SODApplet.jar
    Applet tag
        <applet code="mypackage.SODApplet.class"
                archive="lib/SODApplet.jar"
                Height=300 Width=300>
        </applet>

  • How to create the instance of a class and to use this object remotely

    I have to change a standalone program to do it working on a local net.
    the program is prepared for this adjustment, because the only problem for this change came from the use of the database; and, in the application, all the accesses to the database come from only a class that supplies a connection to the database.
    In this way I think that I could have (in a local net) a "server application" that has the database embedded inside it.
    Furthermore, some client applications (running in different computers of the net) could get access to the database through the connection that comes from an instance of the class that, in the "server application", is made to provide the connection to the database.
    I think this could be a good idea...
    But I don't have practice with distributed applications and I would ask some suggestion about the way to realize my modification.
    (in particular how to get and use, in the "client applications", the instance of the class that give the connection to the database from the "server application").
    I would have some help..
    thank in advance
    regards
    tonyMrsangelo.

    tonyMrsangelo wrote:
    I have to change a standalone program to do it working on a local net.
    the program is prepared for this adjustment, because the only problem for this change came from the use of the database; and, in the application, all the accesses to the database come from only a class that supplies a connection to the database.
    In this way I think that I could have (in a local net) a "server application" that has the database embedded inside it.
    Furthermore, some client applications (running in different computers of the net) could get access to the database through the connection that comes from an instance of the class that, in the "server application", is made to provide the connection to the database.
    I think this could be a good idea... Which is why JEE and implementations of that exist.
    But I don't have practice with distributed applications and I would ask some suggestion about the way to realize my modification.
    (in particular how to get and use, in the "client applications", the instance of the class that give the connection to the database from the "server application").
    You can't pass a connection from a server to a client. Nothing will do that.
    As suggested you can create a simple RMI server/client set up. Or use a more feature rich (and much more complex) JEE container.
    RMI is simple enough for its own tutorial
    [http://java.sun.com/docs/books/tutorial/rmi/index.html]
    JEE (previously called J2EE) is much more complex and requires books. You can get a brief overlook from the following
    [http://java.sun.com/javaee/]

  • WAR meta-inf/manifest Class-Path jars use which classloader ?

    If using an expanded EAR structure, my Web App requires some utility classes. I
    can either put these in my :-
    meta-inf/manifest.mf
    Class-Path : utility.jar
    OR
    web-inf/lib
    can contain the utility.jar
    Is there any difference in terms of which classloader is used to load these classes,
    the EAR/EJB classloader or the Web App child classloader ?
    What is recommended ?

    If have found out the answer myself by testing it :-
    A jar in the meta-inf/manifest.mf e.g. Class-Path : utility.jar
    will be loaded by the EAR/EJB level classloader
    whereas
    web-inf/lib containing utility.jar
    will be loaded by the Web App level child classloader.
    Dimitri Rakitine <[email protected]> wrote:
    I have this question too - it appears that 6.1sp2 attempts to use Class-Path
    in jars in WEB-INF/lib - what this Class-Path: is supposed to do ???
    Pete <[email protected]> wrote:
    If using an expanded EAR structure, my Web App requires some utilityclasses. I
    can either put these in my :-
    meta-inf/manifest.mf
    Class-Path : utility.jar
    OR
    web-inf/lib
    can contain the utility.jar
    Is there any difference in terms of which classloader is used to loadthese classes,
    the EAR/EJB classloader or the Web App child classloader ?
    What is recommended ?--
    Dimitri

  • Wipes out classes and jars in Java Build Path

    Hello!
    All the jar and class files under Library tab gets cleared when I repair my DC project. But when I repair normal projects it does not wipe out  the jars or classes in the Library. Can someone please help me?
    Thanks
    Raj

    Hi Raj,
    The Java build path of a DC-project is based on the definitions in de DC-dependecies (shown in .dcdef file).
    Everytime you repair or build the  DC the build path will be updated into the .project file based on the .dcdef file.
    See the online documentaion for how to add libraries to the DC dependecies.
    Hope this helps.
    Regrads,
    Alain.

  • Adding all the classes and external jars in webservice WAR using servicegen

    Hi,
    Can someone please tell me how do I include all the classes and my external jar files to the ear/war file that is created using servicegen. I don't see any option in servicegen tag where I can include my classes and jar files to the ear/war file. The war it creates only contains the web service implementation class but I want to all the classes in the service code and jars in the same war. Any ideas on how to do that instead of putting in the classpath.
    here is the snippet of my build file
    <servicegen
           destEar="${deploy}/myservice.ear"
           warName="myservice.war">
           <service
             javaClassComponents="com.ws.service.TestService"
             targetNamespace="http://xmlns.test.com/tool/myservice"
             serviceName="myservice"
             serviceURI="/myservice"
             style="document"
             protocol="http"
             expandMethods="True">
           </service>
          <classpath>
            <pathelement path="${classes}"/>
            <pathelement path="${lib}/*.jar"/>
         <pathelement path="C:/bea/weblogic92/server/lib/webserviceclient.jar"/>
          </classpath>      
    </servicegen>
    ..........................Thanks

    Hi,
    The work around I am using to overcome this problem is Unzipping th ear/war file created by servicegen task and including all the classes. Then creating the ear file again by creating a new ant target.
    I know this is not a neater way, but this works for me.

  • How to run .class file and .jar file in jdev9i

    I want to run .class file and .jar file in jdev9i,what should I do?
    Also,I want to generate .class file and .jar file in jdev9i,what should i do?

    Add the .class file containing the public static void main(...) method to the project by clicking on the + toolbar button in the navigator, open the project properties and properly set the additional classpath then right click on the .class in the navigator and say run. It should work, I've just tried it.
    Doesn't work for a .jar yet, in JDeveloper 9.0.3 it works both for .class and .jar
    Michel

  • Classes and Global Data

    OK, I've been battling how to do this with my test code and now it comes back to "bite" me in my new project.
    In regular C, you just create your structures, fill them with data, and then your subroutines have full access to the global data.
    With Objective-C you envelop certain data inside other objects. I got that. In fact, that's where I've gotten "stuck". Let me elaborate.
    I have a the following classes:
    Class (number of instances expected) description of class
    Scenes (1) tables containing dictionaries of scenes and scene components
    Pieces (1) tables containing images, type specs, etc. of game pieces
    Blocks (1) tables with definitions, specs of movable game pieces
    MainView (1) main application view, contains methods to draw the main gameboard
    BlockView (n) view for the block and data needed to manipulate it by the main game logic
    MainViewController (1) main controller for game screen
    Ok, since MainView manages the game window it's init methods also call the init methods to instantiate the one instance of Scenes and Pieces which are needed to be setup in order for MainView to draw the currentScene using the UIImage figures for each of the pieces. So, it saves a pointer to the Scenes and Pieces instances. MainViewController can access those since it sets up MainView and has a pointer to it. MainViewController is currently where I had planned on firing up the BlockView subviews, one for each movable game blocks.
    The problem comes with BlockView which has the logic to setup the additional data for each block type, but does not have a pointer to the instances of Scenes or Pieces which contain the current scene info and the UIImage dictionary to use for drawing the actual images on the screen. How can it get a pointer to the appropriate classes?
    Since BlockView is invoked by MainViewController as it sets up the pieces, I could pass the pointer as part of the init method, but that seems like the WRONG place. Shouldn't I be able to put some block of pointers someplace where all objects can query to get the data needed (keeping it encapsulated within some master gameSettings object).
    Actually that's part of where I'm going with this. I want to have a settings object which knows what scene is current, what block set (images) is in use (so I can have different images for each piece depending on which set is selected), and the saved state information needed to continue where I left off. (This part is mostly a serialization of the Blocks instances which contain both the initial and current locations on the screen, and the current background tableau which shows a more-or-less static background for each scene).
    Instead of one object, right now I've separated the types of information by 3 classes, but everything needs access to two of those classes in order to fully function. I think I have that part under control. What I don't have is the BlockView instances and the GameLogic methods having access to the Scenes and Pieces data unless I pass a pointer to them during initialization.
    Is that what I'm supposed to do?
    Or is there a better way?
    Lastly, my game logic is really a set of methods which act on ONE specific piece to move it, but then that movable piece (one of the instances of BlockView) is able to push other pieces as it moves. Additional methods will handle the pushing of the other instances of BlockView around until a solution is completed for the scene. That part, I think I've gotten OK, as the game logic will be Built into the Blocks or BlockView classes. (That's the part I will have to figure out).
    I'm adding this to my query, so you know my intention, and whether I'm on the right track. So far my Blocks class only contains definitions used by BlockView, and no instance variables or methods yet. If all the logic can be put into the BlockView methods, I can probably throw Blocks away.
    So, do I add a pointer to my init method...
    - (id)initWithString:(NSString*)myType atPoint:(CGPoint)point
    becomes
    - (id)initWithString:(NSString*)myType atPoint:(CGPoint)point inScene:(Scene)scene ofSet:(Pieces)pieceSet
    If that is what it takes, I can do it. It just seems there ought to be a better way.
    Of course, I could abstract those last pointers to only provide the pieces needed for that one instantiation of a BlockView, as I have with 'myType' and 'point' by supplying only the 'pieceSet' to init, but then the game logic will need to have access to the 'scene' to know whether a given block is allowed to move to a given position. This is where I get confused as far as what information to pass to a class, since I know other methods invoked by touches will cause the blocks (in BlockView instances) to move around on the screen displayed by MainView.
    Actually MainView will be detecting the touches and moving the instances of BlockView, so maybe the game logic SHOULD be in MainView instead. I just figured that to encapsulate it as methods that operate on the movable pieces, the methods should be in BlockView, and called by the touch detection routines in MainView.
    Comments please. And don't say, you can do it either way... one way or the other, or yet a third way I don't fully comprehend (such as another viewController) should contain the logic. I think the logic is part of the model and not the view, but in this case, it affects the view based on the background squares and what happens to each block as it is moved or pushed "into" one of those squares.
    Thanks in advance. I realize this may be a complicated question, but I think it is a fairly BASIC question, and my lack of Objective-C experience is showing.
    To tie the question up a little better, I'm not expecting to have all objects have complete access to lots of global data. What I'm looking for is a place to put a pointer to each of my classes which are only ever instantiated once, and have that pointer be findable by any other class that can then query the appropriate class instance to retrieve the data. Right now, I have one and only one place holding these pointers, and am passing them to the objects/classes which need access to the data in those Scene and Pieces classes when they need them.
    If that is the way I'm supposed to do it, then I'm on the right track, even if it means deciding which classes are allowed to hold and pass the appropriate object pointers to other objects.

    etresoft wrote:
    I think you are missing an important piece - the "model" - from the MVC architecture - Model, View, Controller.
    Your "business logic" is composed of your Scenes, Pieces, and Blocks. That is your model. Your view shouldn't really know anything about that. Your controller understands both your model and your view and it puts the two together to draw things. You want to be able to swap our your GUI view for a text view, if you wanted to. Chess, for example, can be played in a GUI or from a text console. A more modern example is a multiplayer game. It has to function across a network so its model has to be projected to the local display as well as sent across the network.
    Yes, I am still fighting with understanding the implementation of some concepts.
    What I think I am wanting to do, is similar to what Apple has done with the file manager or notification centers, and be able to request information from my model as needed.
    For example, my view doesn't care about the specifics of the scenes or pieces, yet my view wants to be able to display the name of the current scene or display the correct image for a piece. Right now, it keeps an instance pointer to my "singleton" Scene object, and using the scene index, gets the current name. To display images, it gets those from the Pieces singleton's image dictionary, and again keeps a pointer to do that.
    What I would rather do is be able to get that pointer for the views that need it without having to copy it, or have back pointers to the superview which holds a copy of those pointers. My BlockView class layers the active pieces over the MainView which holds the playing board. To access things, my code looks like:MainView* mainView = (MainView*) self.superview;
    NSString* key = [mainView.myScene.sceneKeys objectAtIndex:mainView.currentSceneIndex];
    NSString* pieceName = [[mainView.myScene.scenes objectForkey:key] pieceAtLocation:loc];
    UIImage* image = [mainView.myPieces.images objectForkey:pieceName];
    Oh, and this isn't actual code. It is a contrived example. I have since made it more efficient.
    What I think would be more appropriate would be something like this:
    NSString* pieceName = [[Scenes CurrentScene] pieceAtLocation:loc];
    UIImage* image = [[Pieces PieceImages] objectForkey:pieceName];
    or even
    UIImage* image = [[Pieces PieceImages] objectForKey:[[Scenes CurrentScene] pieceAtLocation:loc]];
    When I attempt to create class methods to access data in my "singleton", I get lots of warnings about accessing instance data in a class method. So, instead I made everything an instance method, but that requires keeping a pointer to the instance available somewhere.
    I have been able to recode some of the instance methods which manipulate derived strings from the instance data into class methods, but not the data read in from the plist data files.
    What I'm missing is how to get the current "singleton" instance from the class, and then use that as the instance pointer, i.e. in the examples above, I guess that pieceAtLocation: would be an instance method, but CurrentScene and PieceImages would be class methods that return an instance pointer to the appropriate dictionaries. How to implement that correctly is where I'm still sketchy.
    Isn't that how Apple has defined DefaultNotificationCenter or DefaultFileManager?
    I've looked at some singleton code, and am not sure how it helps me get this done, so an example would definitely help.

  • Dynamic class loading problem using unknown JAR archive and directory names

    I read the following article, which enlightened me a lot:
    Ted Neward: Understanding Class.forName().
    However, it took me some while to understand that my problem is the other way around:
    I know the name of the class, I know the name of the method,
    but my program/JVM does not know where to load the classes from.
    Shortly, my problem is that the server engine that I am writing
    uses two different versions of the same library.
    So I am trying out the following solution:
    My program is named TestClassPathMain.java
    Assume the two libraries are named JAR1.jar and JAR2.jar
    and the class/instance method that should
    be exposed to TestClassPathMain.java by them is named
    TestClass1.testMethod().
    As long as I was depending on just one library,
    I put JAR1.jar in the classpath before starting java,
    and I was happy for a while.
    At the moment I got the need to use another version of
    TestClass1.testMethod() packaged in JAR2.jar,
    a call would always access JAR1.jar's
    TestClass1.testMethod().
    I then decided to remove JAR1.jar from the classpath,
    and programmatically define two separate ClassLoaders, one for use
    with JAR1.jar and the other for use with JAR2.jar.
    However, the problem is only partly solved.
    Please refer to the enclosed code for details.
    (The code in the JAR1.jar/JAR2.jar is extremely simple,
    it just tells (by hardcoding) the name of the jar it is packaged in
    and instantiates another class packaged in the same jar using
    the "new" operator and calls a method on it. I don't enclose it.)
    The TestClassPathMain.java/UC1.java/UC2.java code suite was
    successfully compiled with an arbitrary of JAR1 or JAR2 in the classpath,
    however removed from the classpath at runtime.
    (I know that this could have been done (more elegantly...?) by producing an Interface,
    but I think the main problem principle is still untouched by this potential lack of elegancy(?))
    1) This problem should not be unknown to you experts out there,
    how is it generally and/or most elegantly solved?
    The "*** UC2: Variant 2" is the solution I would like best, had it only worked.
    2) And why arent "*** UC2: Variant 2" and
    "*** static UC2: Variant 2" working,
    while "*** Main: Variant 2" is?
    3) And a mal-apropos:
    Why can't I catch the NoClassDefFoundError?
    The output:
    *** Main: Variant 1 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** Main: Variant 1 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** Main: Variant 2 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** Main: Variant 2 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** UC1: Variant 1 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** UC1: Variant 1 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** static UC2: Variant 2 JAR 1 ***:
    Exception in thread "main" java.lang.NoClassDefFoundError: TestClass1
            at UC2.runFromJarVariant2_static(UC2.java:56)
            at TestClassPathMain.main(TestClassPathMain.java:52)
    TestClassPathMain.java
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class TestClassPathMain {
        public static void main(final String args[]) throws MalformedURLException, ClassNotFoundException, InstantiationException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
                // Commented out because I cannot catch the NoClassDefFoundError.
                // Why?
                try {
                    final TestClass1 testClass1 = new TestClass1();
                    System.out.println(
                        "\nThe class TestClass1 is of some unexplicable reason available." +
                        "\nFor the purpose of the test, it shouldn't have been!" +
                        "\nExiting");
                    System.exit(1);
                } catch (NoClassDefFoundError e) {
                    System.out.println("\nPositively confirmed that the class TestClass1 is not available:\n" + e);
                    System.out.println("\n\nREADY FOR THE TEST: ...");
                // Works fine
                System.out.println("\n*** Main: Variant 1 JAR 1 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** Main: Variant 1 JAR 2 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Works fine
                System.out.println("\n*** Main: Variant 2 JAR 1 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** Main: Variant 2 JAR 2 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Works fine
                final UC1 uc1 = new UC1();
                System.out.println("\n*** UC1: Variant 1 JAR 1 ***:");
                uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** UC1: Variant 1 JAR 2 ***:");
                uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Crashes
                System.out.println("\n*** static UC2: Variant 2 JAR 1 ***:");
                UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** static UC2: Variant 2 JAR 2 ***:");
                UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Crashes
                final UC2 uc2 = new UC2();
                System.out.println("\n*** UC2: Variant 2 JAR 1 ***:");
                uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** UC2: Variant 2 JAR 2 ***:");
                uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
        private static void runFromJarVariant1(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final Object testClass1 = clazz.newInstance();
            final Method testMethod1 = clazz.getMethod("testMethod", null);
            testMethod1.invoke(testClass1, null);
        private static void runFromJarVariant2(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
    UC1.java
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class UC1 {
        public void runFromJarVariant1(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final Object testClass1 = clazz.newInstance();
            final Method testMethod1 = clazz.getMethod("testMethod", null);
            testMethod1.invoke(testClass1, null);
    UC2.java
    import java.lang.reflect.InvocationTargetException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class UC2 {
        public void runFromJarVariant2(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
         * Identic to the "runFromJarVariant2" method,
         * except that it is static
        public static void runFromJarVariant2_static(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
    }

    2. i need to load the class to the same JVM (i.e. to
    the same environment) of the current running
    aplication, so that when the loaded class is run, it
    would be able to invoke methods on it!!!
    ClassLoader(s) do this. Try the URLClassLoader.
    (I was talking about relatively esoteric "security"
    issues when I mentioned the stuff about Class objects
    "scope".) You might use the URLClassLoader kind of
    like this.
    Pseudo-code follows:
    // setup the class loader
    URL[] urls = new URL[1];
    urls[0] = new URL("/path/to/dynamic/classes");
    URLClassLoader ucl = new URLClassLoader(urls);
    // load a class & use make an object with the default constructor
    Object tmp = ucl.loadClass("dynamic.class.name").newInstance();
    // Cast the object to a know interface so that you can use it.
    // This may be used to further determine which interface to cast
    // the class to. Or it may simply be the interface to which all
    // dynamic classes have to conform in your program.
    InterfaceImplementedByDynamicClass loadedObj =
        (InterfaceImplementedByDynamicClass)tmp;It's really not as hard as it sounds, just write a little test of
    this and you will see how it works.

  • Using Class and Constructor to create instances on the fly

    hi,
    i want to be able to create instances of classes as specified by the user of my application. i hold the class names as String objects in a LinkedList, check to see if the named class exists and then try and create an instance of it as follows.
    the problem im having is that the classes i want to create are held in a directory lower down the directory hierarchy than where the i called this code from.
    ie. the classes are held in "eccs/model/behaviours" but the VM looks for them in the eccs directory.
    i cannot move the desired classes to this folder for other reasons and if i try to give the Path name to Class.forName() it will not find them. instead i think it looks for a class called "eccs/model/behaviours/x" in the eccs dir and not navigate to the eccs/model/behaviours dir for the class x.
    any ideas please? heres my code for ye to look at in case im not making any sense:)
    //iterator is the Iterator of the LinkedList that holds all the names of the
    //classes we want to create.
    //while there is another element in the list.
    while(iterator.hasNext())
    //get the name of the class to create from the list.
    String className = (String) iterator.next();
    //check to see if the file exists.
    if(!doesFileExist(className))
    System.out.println("File cannot be found!");
    //breake the loop and move onto the next element in the list.
    continue;
    //create an empty class.
    Class dynamicClass = Class.forName(className);
    //get the default constructor of the class.
    Constructor constructor = dynamicClass.getConstructor(new Class[] {});
    //create an instance of the desired class.
    Behaviour beh = (Behaviour) constructor.newInstance(new Object[] {});
    private boolean doesFileExist(String fileName)
    //append .class to the file name.
    fileName += ".class";
    //get the file.
    File file = new File(fileName);
    //check if it exists.
    if(file.exists())
    return true;
    else
    return false;
    }

    ok ive changed it now to "eccs.model.behaviours" and it seems to work:) many thanks!!!
    by the following you mean that instead of using the method "doesFileExist(fileName)" i just catch the exception and throw it to something like the System.out.println() ?
    Why don't you simply try to call Class.forName() and catch the exception if it doesn't exist? Because as soon as you package up your class files in a jar file (which you should) your approach won't work at all.i dont think il be creating a JAR file as i want the user to be able to create his/her own classes and add them to the directory to be used in the application. is this the correct way to do this??
    again many thanks for ye're help:)

Maybe you are looking for