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

Michał Ziembiński
  • 1,054
  • 2
  • 9
  • 27

1 Answers1

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.

Community
  • 1
  • 1
Stanislav Lukyanov
  • 1,420
  • 7
  • 16