A rather hacky solution would be to put the text in a file after removing imports and with a name different from the public class
Then use the JavaCompiler package to compile the file on the fly and catch compilation errors
- You could catch "class not defined" type of errors for default Java classes.
- For classes defined by you, if it is a public class, you would get an error like "class must be defined in its own file"
So in the end you would get
- The line number of the class in the compilation error
- The name of the class in the error statement
This could be too complicated in the long run, but in the absence of libraries to do what the OP states, this could be used.
In addition, things could get tricky for classes under java.lang
since they are included by default