Shockwave
Shockwave

Reputation: 27

Java - Compiling and referring to a class of an unknown name

So there is a problem that my colleagues and I have been trying to tackle, we've been dabbling with a 'benchmarking' kind of program. We want to receive a .java file from a user, compile it and invoke it from our own main class.

So we would not know what the name of the files are but they will have a common method that we can invoke such as main() for example, we were hoping to compile them to class files such as Test1.class, Test2.class etc. But we see that the names of the class files need to correspond to the class within.

Is there perhaps another way around to getting this to work? Such as compiling it into a .jar file and if we could refer to it implicitly through this method? (Not sure of that is possible)

Worst-case scenario, we can restrict input files to known file names, we just wanted to appeal to perhaps more diligent minds if perhaps there is a more elegant solution that we can make use of.

Upvotes: 1

Views: 67

Answers (1)

GhostCat
GhostCat

Reputation: 140427

Simple: use a tool such as JavaParser to process your input. And then: rename the incoming class to something you know.

You see: most likely you want to check the source code you get anyway. Or do you really want to allow users to upload arbitrary code to your system that gets executed there? So - when you carefully analyse that input for security problems - it should be "peanuts" to rename the received code on the fly.

If that doesn't work: why not ask your users to provide all that information to you? Meaning: you are dealing with a complex problem because you allow many degrees of freedom to your users. But would their experience really suffer when you ask them to provide the class / file name they intend to use in their upload?

Upvotes: 3

Related Questions