0

I trying to get java.lang;Class object from not yet compiled file (*.java). I develop a plugin to netbeans plaform and i know how to find specify classLoader for source folder (src) and after that i would like to get Class object for specify file. I can call loadClass to get it but this dosent work on not compiled file. For example:

        ClassPath classPath = ClassPath.getClassPath(someFileObject, ClassPath.SOURCE);
        ClassLoader loader = classPath.getClassLoader(true);
        Class myLookingForClass = loader.loadClass("web.users.User"); 
        // it is file User.java in package web.users

it is some way to get it?

UPDATE:

Ok, I trying to implements mechanism whitch will generate dynamic class with their body (methods,variables etc.). To do that i need class definition of for example: method returning type or some variables types.

Example scenario:

User working on IDE (Netbeans) and he created a some class (but not compiled). This class will be userd in body of some class whitch we will dynamic create after some event(For example in using some button). And now it is no problem to getClassLoader and load class definition as java.lang.Class and them using. But files need to be already compiled. And now i would like to know if it is some way to get java.lang.Class from file for example" someFile.java and package somePackage

2
  • The class loader cannot load a class which is not compiled; how should it do that? Commented Oct 31, 2014 at 13:04
  • This smells like an XY problem. Why are you trying to do this? What's your underlying problem? Commented Oct 31, 2014 at 13:05

1 Answer 1

1

There is no way to have a Class object for not yet compiled class.

You must understand that java.lang.Class is really a reflection API that represents a class loaded by JVM rather than just an abstraction for a java class in general. ClassLoader itself also works only with a classfile structures. .java files have nothing to do with a running Java: while not compiled they're just a text files.

On the other hand you can compile a java file programmatically using a Java Compiler API and then access the compiled class. See javax.tools to learn how to use this API. Maybe this SO question will help too.

Sign up to request clarification or add additional context in comments.

1 Comment

ok i see i need to use JavaCompiler first and dynamic compile file and after that get java.lang,Class from this dynamic compiled file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.