How to load a class from its source code using Javassist? - java

I have in an input stream the complete source code of a class. Is it possible to use Javassist to create a new CtClass object for this class ?.
I know that with the name of the class is possible to create a new CtClass object with something like:
ClassPool.getDefault().makeClass("name_of_the_new_class");
But in my case I do not know the name of the class in advance, but just its complete source code (of course I could get the name of the class parsing the source code, but please do not tell me that this is part of the solution :-) )

If you want to compile a source file on-the-fly, have a look at the tools API as well as ToolProvider.getSystemJavaCompiler(). From there you can compile .class files from source and load them using a classloader if you need to.
You could also then use Javassist to create a CtClass from the bytes of the created class file using ByteArrayClassPath with a new ClassPool.

Related

How to load a java class outside the classpath?

I have a program where I want the user to be able to choose a .java class file from the file system, and then have that class loaded into the program.
I'm using a JFileChooser to allow the user to select a file. Then, I tried converting that file to a URL, and using a URLClassLoader to load the class (as suggested by these answers).
The problem is that, when I want to use the loadClass() method, I don't know the "full class name" of the class (e.g. java.lang.String). So, I don't know how to make this method work. Is there a way to get this class name? Or is there another way to do this?
Here is a sample of my code:
// Open the file chooser
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
File obtainedFile = fileChooser.getSelectedFile();
// Create the class loader from the file
URL classPath = obtainedFile.toURI().toURL();
URLClassLoader loader = new URLClassLoader(new URL[] {classPath});
// Get the class from the loader
Class<?> theClassIWant = loader.loadClass("the file name"); // What do I put here??
Load a single class file is generally completely useless. Said class file isn't alone; it has more class files that are relevant. Even if you think 'nah, there is just one source file, do not worry about this', note that a single java file can easily generate multiple class files.
Thus, two options:
Don't load class files. Load jar files.
Use the usual mechanisms (META-INF/services or META-INF/MANIFEST.MF) to put some sort of class name in there so you know what to load. Then create a new classloader with the provided jar, load the manifest, figure out the main class, load that, and run it.
Attempt to determine the 'root' for the loaded class file and include that on the classpath.
This is quite difficult - the problem is, to 'load' a class file you need to tell the loader what the fully qualified name is of that class before it is loaded. But how do you know the fully qualified name? You can surmise the class name from the file (not quite always true, but usually), but the package is a more difficult issue.
You can open the class file yourself as a binary stream and write a basic class file format parser to get the fully qualified class name. Easy for an experienced java programmer. Quite tricky for someone new to java (which I gather you are, if you think this is a good idea).
You can also use existing tools to do this, such as bytebuddy or asm.
Finally, you can try a spaghetti-at-the-wall method: Keep travelling up the directory until it works. You know it isn't working if exceptions occur.
For example, to load C:\MyDir\Whatever\com\foo\MyApp.class, You first try creating a new classloader (see the API of URLClassLoader which is part of core java) using as root dir C:\MyDir\Whatever\com\foo, and then you ask it to load class MyApp.
If that works, great (but usually trying to load package-less classes is simply a non-starter, you're not supposed to do that, the CL API probably doesn't support it, intentionally, there is no fixing that).
If it doesn't, instead try C:\MyDir\Whatever\com, and load class foo.MyApp. If that doesn't work, try C:\MyDir\Whatever and load class com.foo.MyApp, and so on.
The considerable advantage is, if there is another class sitting right next to MyApp.class, and MyApp needs it, this will work fine.
You'll need to write a while loop (traversing the path structure using Paths.get and p.getParent()), catch the right exception, manipulate the path into the class name (using .replace and +), and, of course, create a class loader (URLClassLoader), load classes with it (invoke loadClass), and if you intend on running it, something like thatClass.getConstructor().newInstance() and then thatClass.getMethod("someMethod", String.class, /* all the other args here */).invoke(theInstanceYouJustMade, "param1", /*all other params */) to actually 'run' it, more to be found in the java.lang.reflect package.

How to generate bytecode of existing class at Runtime in Java?

How to generate bytecode of existing class at Runtime in Java?
My Existing class is say Foo.java
public class Foo {
public String saySomething() {
return "Hello World";
}
}
Now I want to generate byte code of this existing class Foo.java and probably use it in another instance of JVM. Please understand I am not creating a class at runtime since I already have an existing class called Foo.java. Open to any libraries such as ASM or ByteBuddy etc.
[Edited following the clarification in the comments]
The following article describes how to compile a class from source code at runtime, using ToolProvider.getSystemJavaCompiler().
You do not need a library for that, any class file is just a resource just like any other file which can be located by Foo.class.getResource("Foo.class"). You can open a stream of this resource and read its byte just as of any other resource.
If you are already using Byte Buddy, you can get hold of the bytes by: ClassFileLocator.ForClassLoader.read(Foo.class) but if that is all you need, using a library would be an overkill.

How to make a class copy itself into another class with a different name that can be executed with Java?

What I would like to do is to copy the compiled class [lets call it ClassA.class] given its file-name (within the code as a String), into a new file (also defined as a String within ClassA) [lets call it ClassB.class], and to be able to execute that new copied class (with a new file name) using "javac ClassB".
What would be the best and the most concise way to do this ?
EDIT: SOLUTION THAT WORKED....
Hex-Editing the file from ClassA to ClassB worked !
So I guess anything that would change the binary code would work, having the filenames of the constant (same) length.
You can copy a class with byte-code manipulation libraries (Javassist, Asm, BCEL).
With Javassist it would be along the lines of (haven't tried):
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("ClassA");
cc.setName("ClassB");
cc.writeFile("ClassB.class");

How to instantiate a class without knowing its package?

I have an Eclipse project (MainProject) and it references another Eclipse project (ReferencedProject). MainProject also references a JAR file (ReferencedJar). This ReferencedJar's file name is known. I also know there is a class (ReferencedClass) in ReferencedJar, but I don't know in what package ReferencedClass is because the package path is not known beforehand.
I need to instantiate ReferencedClass in ReferencedProject using reflection. How can I do this? And will the solution be okay when the project is packaged to a its standalone jar outside Eclipse?
The reason for this question is; The ReferencedJar is file generated by a modeller application. It generates java classes for your model and puts them into ReferencedJar. The user can choose which package the classes it generates will be put into. But the class names are always the same. MainProject is project that will include this generated jar, but ReferencedProject (a framework) also needs to instantiate a class in this generated jar. Hope this makes the question more clear.
Thanks in advance
Edit: Actually I have an idea but don't know how to implement it. Because I know the name of ReferencedJar file, I could access it on runtime and check all the classes it contains. Then I can find the matching class by name comparison. But how can I access the ReferencedJar on runtime?
As long as the class you need is in the class path, you can get a reference to it by invoking Class.forName(String className)
String className = "WhatEver";
String packageName = "some.package";
Class<?> c = Class.forName(packageName + "." + className);
If you don't know the package name, however, and there's no way to get it from a configuration file, I would recommend using a library like reflections to scan the class path and find the relevant class.
You can not instantiate a class you if do not know its package

Access classes from package

I'm developing an android test app and i'm going to access all internal class of android.view package. android.view is a package that is present in jar file. I tried by loading package name but it doesn't display the classes if any one tried
this already, please help.
Here's what I tried so far:
public static void main() throws ClassNotFoundException{
Class o =Class.forName("android.view");
Class[] C=o.getDeclaredClasses();
for(int i=0;i<C.length;i++) {
Classname = C[i].getName();
ClassesDisplayActivity.your_array_list3.add(Classname);
Log.i("Ramu","classname "+ C[i].getName());
}
}
}
It is not possible to determine at runtime all of the classes that are in a package using a standard class loader.
You might have some luck with this library though:
https://code.google.com/p/reflections/
Package is not a class. You cannot call Class.forName() for package and access classes that belong to class using getDelcaredClasses().
I do not know what do you really need, so I'd recommend you to explain this in separate question. probably you will receive better solutions.
However if you really need this you have to do the following:
Get your classpath by calling System.getProperty(java.class.path)
split this property to its elements by colon
iterate over the list and read each resource. If resource is jar you can use ZipInputStream, if it is a directory use File class.
filter list of resources you got at #3.
Fortunately you can use 3rd party library named Reflections that helps you to do all this without writing code.

Categories