0

I use this code to create a Class and an Instance from a java byte code

Class aClass = container.getByteCode();
    o = aClass.newInstance();

I want to do the same thing but with java source code ( String ) instead.

aClass = container.getJavaCode()...
user567
  • 3,712
  • 9
  • 47
  • 80
  • you will need some compiler to transform the source code into byte code. – mschenk74 Jul 11 '14 at 22:04
  • 2
    And you'll need someone else to rethink your design because it's very, very rare that this is the only solution to a problem. – christopher Jul 11 '14 at 22:05
  • [What is the underlying problem you're trying to solve?](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – chrylis -cautiouslyoptimistic- Jul 11 '14 at 22:08
  • What you want to do is done with Java Server Pages (JSP), I believe. (If not JSP then one of the other similar kits.) There is a way to access *javac* within a Java program. But it's not simple, and I'm not sure how "general" it is. – Hot Licks Jul 11 '14 at 22:27
  • Similar question from yesterday: http://stackoverflow.com/questions/24665848/java-run-a-string-as-normal-code – aliteralmind Jul 11 '14 at 22:34
  • You can, of course, always use Runtime.exec to invoke the standard *javac* compiler. But it takes a bit of a tap-dance to do that right -- you must wait for the resulting process to finish and appropriately handle the return values from it. – Hot Licks Jul 11 '14 at 22:45

1 Answers1

0

You're going to need a Java compiler for that. The Eclipse Compiler for Java was written in Java, and can run as a standalone compiler, so it should be pretty easy to either hook into another entry point or add another entry point. I'm not sure how hard it would be to make it compile against the current classpath (classloader, really) rather than rt.jar.

There's also broadening your requirements a bit and using a Groovy interpreter (Groovy's at least a superset of Java), or even switch to Javascript (Java ships with a JS engine) or Ruby.

David Ehrmann
  • 7,366
  • 2
  • 31
  • 40