1 2 Previous Next 16 Replies Latest reply: Mar 28, 2011 6:53 PM by EJP RSS

    How can I convert a string to an object or class

    801511
      I would like to read a file representing a class, and convert it to an object or a class (object preferred). Other postings suggest using javax.tools.JavaCompiler to convert from a string but then say that this is not always available (posting on 1 Jan 09). If this is still not universally available is there another way to do this? If this is not available, are there any examples of how it should be done?

      My understanding from what I've read is to read the file into a String then compile the String using javax.tools.JavaCompiler, which is an Interface.

      thanks
        • 1. Re: How can I convert a string to an object or class
          Kayaman
          skidmarks wrote:
          I would like to read a file representing a class
          Represented how? A regular class file or a source file?
          and convert it to an object or a class (object preferred).
          If the file depicts a class, then you can convert it to a class and after that create a new instance of it. If the file is a serialized object, you can deserialize it to an object, but you still need its class file.


          What are you trying to do?
          • 2. Re: How can I convert a string to an object or class
            824073
            To compile a Java file there must be a Java compiler present on the system that will run your application (this generally means a JDK should be present). If you cannot guarantee that this is the case (so if your application also has to work on a regular JRE) you cannot use this approach and you will have to compile your classes before you deploy the application.

            Is there a specific reason you need to compile from source at runtime? You can always compile your source files to classes on your machine and load the class files dynamically using a classloader. This approach will work on all systems that have a java JRE or JDK.
            • 3. Re: How can I convert a string to an object or class
              796440
              skidmarks wrote:
              I would like to read a file representing a class, and convert it to an object or a class (object preferred).
              You're talking about two completely different things.

              A file representing a class would indicate things like member variable names and types and method names and definitions. To turn it into a class, you would have to do work similar to what javac does when it compiles your .java files to .class files. To turn it into an object, you would first have to turn it into a class, and then use reflection to generate an object, just like you would for any other class whose name is not known at compile time.

              (EDIT: The above assume you're talking about a text file. Another interpretation of "file that represents a class" is simply a .class file that's already been compiled.)

              A file representing an obejct would indicate the class name member variable name/value pairs. You wouldn't turn it into a class. You would turn it into an object. You would read the class name values from the file and then use reflection to create an instance of the object and set the fields accordingly. (Of course, if there are small number of classes you'll be doing this for, and you know them at compile time, you can skip reflection and just use constructors and setters and getters directly.) You can of course get the class of any object with getClass().

              So which is it you really want to do?

              Edited by: jverd on Mar 28, 2011 11:25 AM
              • 4. Re: How can I convert a string to an object or class
                801511
                kayaman, mmo, jverd - thanks.

                What i would like to do is to take a Java file representing a class and compile it at runtime. However, the comment about a JDK being available at runtime makes this unattractive. The next guess would to be to create a .jar file and reference it at runtime. Here's the scenario:
                1. People using the 'system' will have a varied knowledge of Java.
                2. My hope was to require that anyone using the program would only need to create a Java Class file, and the 'system' would do the rest, which I think means that the files be compiled at runtime.
                3. Requiring that users be familiar with Java in order to create a jar file reduces product usefulness.
                4. It looks like the requirement that the JDK be available at runtime is the killer condition. It's probably better to abandon the notion of runtime compilation and just generate a jar file.

                In either case, the Class Files would look like:
                public class Name {
                    int field1;
                    float field2;
                }
                With all the field types being simple Java Primitives.

                I thought that the definition was simple enough to allow non-Java programmers an opportunity to create the required files and allow the system to do the rest. But if I shouldn't, I shouldn't.

                If this is so, is there any way to create a .jar file at runtime? Do I have to exec("jar") or is there another way.

                And thanks to all;
                art
                • 5. Re: How can I convert a string to an object or class
                  796440
                  skidmarks wrote:
                  What i would like to do is to take a Java file representing a class and compile it at runtime. However, the comment about a JDK being available at runtime makes this unattractive.
                  So, you want to compile .java files, but you don't want to have to use a compiler?
                  The next guess would to be to create a .jar file and reference it at runtime. Here's the scenario:
                  Eh? How is that even remotely equivalent?
                  1. People using the 'system' will have a varied knowledge of Java.
                  2. My hope was to require that anyone using the program would only need to create a Java Class file,
                  You mean a Java source file. You have said that YOU want to create the .class file. If they are creating the .class file, then all you need to do is load it with a ClassLoader and start using it.

                  You might try clarifying your requirements a bit.
                  In either case, the Class Files would look like:
                  public class Name {
                  int field1;
                  float field2;
                  }
                  With all the field types being simple Java Primitives.
                  What is the point of this? What are you ultimately trying to accomplish, that can be served by user-defined groups of primitives, with no complex object graphs and no user-defined methods?

                  Depending on what you're really getting at, using scripting features via beanshell, groovy, or javascript might be an approach to consider, or using Scala to produce a domain-specific language (although I suspect that last may be overkill, and beyond your current skill level).
                  If this is so, is there any way to create a .jar file at runtime? Do I have to exec("jar") or is there another way.
                  A .jar file is just a .zip file with a manifest. Look at the java.util.jar package. But note that creating a .jar file has nothing to do with the rest of what you're asking about.
                  • 6. Re: How can I convert a string to an object or class
                    801511
                    The scenario is:
                    Given a definition of a message, allow user to generate message data for transmission to an external destination and to receive message data from an external source. The software has enough information to associate data with the Java class related to the data, and with this information. With this class file the software can then verify and convert user ASCII data for transmission using UDB, and can accept received data and pretty-print it into a log file.

                    Test team personnel will be responsible to creating the Java class files. The software will be responsible for all activities based on the Java class files. Before we go further, the scheme is operational and not speculative.

                    Since the software uses the Java class file as a template for comparison of user inputs for legitimacy, generation of messages for transmission, and pretty-printing of input message for logging, it would be nice to automate the process of generating internal objects and classes rather than have them as part of the general software build. In this way, the process of enhancing and software becomes independent of the process of defining the data that the software is to work on. Java classes were chosen over, eg, XML because of the simplicity of representation and availability of training materials. At this date it is speculative that a future project will use other means to accomplish the current projects goals.

                    With emphasis now shifting to a more user oriented phase of use it would be very useful to reduce the need for Java developers to support message definition.

                    art
                    • 7. Re: How can I convert a string to an object or class
                      796440
                      skidmarks wrote:
                      The scenario is:
                      Given a definition of a message, allow user to generate message data for transmission to an external destination and to receive message data from an external source. The software has enough information to associate data with the Java class related to the data, and with this information. With this class file the software can then verify and convert user ASCII data for transmission using UDB, and can accept received data and pretty-print it into a log file.
                      No idea what that really means, or how it relates to what you're asking.
                      Test team personnel will be responsible to creating the Java class files.
                      So the test team will create .java files with valid Java syntax and invoke javac to compile them into .class files.
                      The software will be responsible for all activities based on the Java class files.
                      That's sort of a tautology. It's simply a very vague explanation of how Java programs typically run. That is, they are software that is contained in .class files and then executed.

                      Ignoring this post and going back to earlier ones, it sounds like you need users to be able to define data structures on the fly, yes?

                      Do they have to be expressed in Java syntax and compiled to .class files?

                      If so, why?
                      • 8. Re: How can I convert a string to an object or class
                        DrClap
                        skidmarks wrote:
                        Java classes were chosen over, eg, XML because of the simplicity of representation and availability of training materials.
                        I was about to suggest that an XML representation could make all of these complications go away. But then I read your post and found that your designers didn't agree with me. So what's the problem? Training materials are available, right? Presumably this means materials which train people to take their Java source code and compile it into Java classes -- or does it mean something else?
                        • 9. Re: How can I convert a string to an object or class
                          aksarben
                          I am baffled as to why you think you need to compile anything at run time. Your description sounds like you simply want to parse a message and perform some processing on it and/or re-send it. Why in the world would you want to compile classes at run time to do that? Such a design would be so slow as to be unusable.

                          Compile your code once, then instantiate & invoke the appropriate class objects to handle the various message types you receive.

                          If you're trying to do something else, you need to explain it much more clearly.
                          • 10. Re: How can I convert a string to an object or class
                            796440
                            aksarben wrote:
                            I am baffled as to why you think you need to compile anything at run time. Your description sounds like you simply want to parse a message and perform some processing on it and/or re-send it. Why in the world would you want to compile classes at run time to do that? Such a design would be so slow as to be unusable.

                            Compile your code once, then instantiate & invoke the appropriate class objects to handle the various message types you receive.

                            If you're trying to do something else, you need to explain it much more clearly.
                            Far as I can tell, he wants to define some (fairly simple) data structures at runtime, e.g.
                            Foo {
                              int x;
                              double y;
                            }
                            These can be thought of as very simple Java classes. No static member variables, no methods--only non-static member variables of primitive types. So, "Hey, this looks like a Java class! Let's piggyback on that!" At least, that's my extrapolation of what's been said so far.
                            • 11. Re: How can I convert a string to an object or class
                              801511
                              I wish there were more designers; then I'd have someone to blame.

                              But you did say something that triggered a thought (I have so few of them that I never fail to confess the one I have). Why don't I just reconfigure the problem so that I make a tool which has the responsibility of reading a directory (or directories) of these Java class files, complies the files - generating .class files in the process -then jar's them up. If that sounds like a reasonable approach then what do I need to do to compile the files programmatically? This looks reasonable in the sense that the 'user' creates the files and calls a tool to do the dirty work.

                              I suppose that I could package this up into a script file and then iteratively compile each file in a directory to class files, and then, in the script, create a jar file. This may be the way to go, what do you think.

                              If this looks ok then how do I load from a jar file? Use the classloader? Ah, I suppose I'll hunt this one up by myself.

                              And, as always, thanks. You have jarred a mind scaled with years observing that the Universe is perverse.

                              art
                              • 12. Re: How can I convert a string to an object or class
                                796440
                                skidmarks wrote:
                                Why don't I just reconfigure the problem so that I make a tool which has the responsibility of reading a directory (or directories) of these Java class files, complies the files - generating .class files in the process
                                Okay, you really need to stop referring to source files as "class files." That's terribly confusing. A class file (ends with .class) is the result of compilation.
                                -then jar's them up.
                                Once again: Jar has nothing to do with anything you've described trying to do so far. Jar files are just zip files, and the only way they're special to Java is that the JVM reads the manifest at startup. Otherwise, they're just an archive where classloaders can search for resources just like they would in a directory. Putting a .class file (or any other file) into a .jar file is no different from having it in a directory when it comes time for the JVM to read it.
                                If that sounds like a reasonable approach then what do I need to do to compile the files programmatically?
                                javac, or the compiler class you already found.

                                It sound like you're back to square 1: wanting to compile Java files without requiring a java compilation environment.
                                • 13. Re: How can I convert a string to an object or class
                                  801511
                                  jverd;

                                  You are correct. This is not rocket science. I want to piggy-back on a known and easily understood means of defining data. Later on I'll probably have questions about handling arrays which are much more problematical.

                                  aksarbian;

                                  The reason that it is undesirable to compile and use the definitions is that this is a tool which is designed to accept arbitrary definitions and using those definitions. If a user specifies a new message(s) there is nothing in the tool that requires changing. Putting the message definitions into the tool means that the message definition and the tool are entwined, which seems unnecessary and undesirable. This is not to say that this can't be done.

                                  thanks
                                  art
                                  • 14. Re: How can I convert a string to an object or class
                                    801511
                                    jverd;

                                    Ok, I'll stop calling the things 'Java class' files and call them Java files - or any alternative you prefer.

                                    The reason a jar file seems agreeable is that in that way a directory of .class files can be stored into a single file and the directory destroyed. This, I think, will simplify maintenance.

                                    And no, I think I've made a lot of progress. You've shown me that my original idea is probably unworkable, or at least, cumbersome. And then you have provided a solution which makes the job doable although contrary to my original intent. Even though it looks like I've gone in a complete circle, thanks. You have clarified the situation for me and now I can go forward (on to my destiny...).

                                    But yes, I'm back to using a compiler. Making a tool out of a scripting language rather than programmatically.


                                    thanks
                                    art
                                    1 2 Previous Next