How to cast an Object when we only have the .class files? - java

Let's say I have a class file named ObjectFoo.class but I don't have access to ObjectFoo.java source file, since the class file is created during runtime. Is there a way to cast an object in this case ?
At the moment, I'm using this code to cast the object, but in this example I need to have ObjectFoo.java in my classpath :
Class c = Class.forName("ObjectFoo");
ObjectFoo object = (ObjectFoo) c.newInstance();
The goal is to instantiate an object from its class file using Java reflection.
I'm looking for a solution using only Java API and no other third-party libraries.
Thanks in advance for your answer !
Jonathan.

When you use third-party libraries, packages as .jar files, you will always compile and run against .class files. The .jar archives contain .class files, not .java ones.
So, the code above is correct, if the ObjectFoo class doesn't belong to a package. Otherwise, you will have to put the full package like path to the class.

To use a Java class, you do not need the source file. You only need the compiled class file, and you need to make sure that the Java compiler can find the class file at the right place.
Make sure that the directory that contains the file ObjectFoo.class is in the classpath when you compile and run your own code. You can do that by using the -cp option of the javac and java commands:
javac -cp C:\SomeDirectory;. MyProgram.java
java -cp C:\SomeDirectory;. MyProgram.java
where C:\SomeDirectory is the directory that contains ObjectFoo.class.
Note: There is also no reason to use reflection, with Class.forName(...) etc. to create a new instance of ObjectFoo. Just use the new operator instead; then you also don't need to cast.
ObjectFoo object = new ObjectFoo();

Related

How to implements interface from .class file in .java file?

I have homework that asks me to use a .class file for my project, but I don't know how to use those files in a .java file. This is the project structure
agentes.class
datos_confidenciales.class
II_Parcial_2007_1.doc
Main.java
numeros.class
I mean, I got to make a class called Main that implements the numeros interface, the numeros interface is in numeros.class file
I've googled but no results.
The .class files simply need to be on the classpath when you compile. How exactly you configure that depends on how you compile (on the commandline or in an IDE; in what IDE).
Here is the documentation for the classpath. Here is a related question for setting the classpath.
The class path is the path that the Java runtime environment searches for classes and other resource files. The class search path (more commonly known by the shorter name, "class path") can be set using either the -classpath option when calling a JDK tool (the preferred method) or by setting the CLASSPATH environment variable. The -classpath option is preferred because you can set it individually for each application without affecting other applications and without other applications modifying its value.
One option is to decompile the class-file, which will get you a java-file of the interface that was compiled.
If you don't want to use a decompiler, write a small application that will reflect the numeros class and prints out all methods and their parameter-types and return-types, so you can implement it.
Of course you could always use an IDE, with the class-file in module-path, your IDE will assist you to implement the interface.

How does Javac work for multiple files, directories, classes and source?

I'm trying to figure out how javac works with regard to stuff like sourcepath, classpath and prebuilt classes etc. I'm trying to read the documentation, but can't really make sense of it.
I've tried to think of some sample cases below.
If I'm compiling a single file onlyfile.java which has no dependencies, which has 2 classes A and B , and class A uses class B , does class B need to be defined/declared before A ? Or is javac smart and does multiple passes or something like that ?
root.java uses another class in a file file2.java located in the same folder. If I execute javac root.java , how does javac know to search the folder for the class file and if not found , for source file instead ?
How does the above work if the file2 is located in a subdirectory ?
EDIT:
I read somewhere that import is just a way to cut down on typing rather than "loading" anything like in python.
Suppose that I'm building only 1 java file which uses multiple other classes, and that these class files already exist. Without import, the a.b.c.d part of the class object already tells me where to search for the class file, then why a cp option ?
1) If you compile class A which uses class B then class B will be compelled as well. If you compile class B (which is used inside A, but A is not used inside B), class A will not be compelled. Find more details end examples here.
2) javac searches inside source-path and class-path. If you run javac without arguments like javac A.java it sets classpath and sourcepath to current directory. If requested class is not found neither in classpath nor in sourcepath you'll have compilation error.
3) Java has strict rules for project structure. You can't simply place source file to another folder without updating file content.
Every folder in the project should have folder hierarchy with respect of package declaration.
Definition: A package is a grouping of related types providing access protection and name space management.
for instance if you have class A.java with package declaration like this
package com.mycompany;
The corresponding folder structure should look like this:
com/mycompany/A.java
If you follow this rules compiler will be able to resolve dependencies just like I explained in #1. Find more information here.
For first two options try with javac *.java
Duplicate of Compiling Multiple Classes (Console) in Java

Use a jar in JavaScript through Java ScriptEngine

I need to use classes from a jar file inside JavaScript. I'm using JavaScript through Java ScriptEngine and would like to do something similar to what I did with Jython here,
import org.python.core.Py;
import org.python.core.PySystemState;
...
PySystemState engineSys = new PySystemState();
engineSys.path.append(Py.newString("C:/GMSEC_API/bin/gmsecapi.jar"));
Py.setSystemState(engineSys);
ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
When I do this with Jython it works fine and the python files can use the api classes that are inside the jar file.
I am able to use the jar's classes within JavaScript this way, but you have to set the jar to the class path when you go to run it. I was after a solution similar to Jython/Python's where you're able to set the jar inside Java but I'm just going to create batch files and sh files and set it that way (seems easier to do it that way now). Here is my solution that works for me.
To Compile Then Run:
cd C:\your\directory\folder\with\the\javascript\and\java\files
javac -d . ClassSpy.java FileSearch.java HelloWorld.java Main.java Parameters.java Run.java
java -cp ./;C:\ABCAPI\bin\abcapi.jar hammer.main.Main gui=true input=JavaScriptStatus.js
Comments on the above lines:
when compiling you can use -d . if you have your java files as packages that you defined and it'll put them in folders with your package name. If that's not clear just check out this post (I'm getting off task) How to compile packages in java? .
Another note is that when I ran it I added two things to my class path -cp stands for class path and anything after that will be added to your class path for this current run. You can separate them with a semicolon. ./ adds the current directory to the class path and the rest I added after that was the location of the API's jar file I needed.
hammer.main is the package location of the class Main which is the class containing my main function to start the program.
The two arguments after that are specific to my program and you can see the JavaScript file I'm going to tell Java ScriptEngine to read and execute.
To Use The Jar File Inside JavaScript:
Now that the jar file is on the class path and visible we can get a package from inside that jar file then call the classes from the package. So for the example below abc.foo.pack.name is a package inside of abcapi.jar and the two classes I'm using ClassFromTheJarFile and AnotherClassFromTheJarFile are in that package. I'm using a technique of setting the package to a variable then prefixing the classes I want to use with the variable containing the package. Another way is to say importPackage(com.foo.bar) then you wont have to prefix the classes every time you instantiate them but this technique doesn't work for me for some reason (perhaps I did something wrong though). At any rate the following code works fine for me,
myvariable = Packages.abc.foo.pack.name;
var foo = new myvariable.ClassFromTheJarFile("arg1","arg2");
foo.doSomething();
var fooSister = new myvariable.AnotherCLassFromTheJarFile("arg1");
fooSister.doSomthingFromThisClass();
Conclusion:
It turns out my mistake was trying to import the class directly like this,
myvariable = Packages.abc.foo.pack.name.ClassFromTheJarFile;
Then I tried using it like,
var foo = new myvariable.ClassFromTheJarFile("arg1","arg2");
Which wasn't working.
I hope this helps someone because I was getting a lot of remarks like, "You know Java and JavaScript are two different things right". Well yes I do know that, what is your point?
Keep In Mind:
I am not using this in a browser or over the internet. I am using this through Java ScriptEngine. If you need to get the jar file from a URL this link I found might help you http://mozilla-firefox-extension-dev.blogspot.com/2004/11/calling-java-code-in-custom-jars-from.html

Instantiate an object from source code compiled on-the-fly

I would like to know if there is a posibility to instance a class of an external file
For example:
Oreja oreja_object = getClassFromExternalFile("C:\oreja_file.java");
Thanks,
Cristina.
Cristina, you can load external .class files dynamically using a custom ClassLoader, such as URLClassLoader. Have a look at this question.
You cannot load a .java source file directly. It must be compiled first, for example using the Java Compiler API.

Finding information about a Java class without documentation

As part of a project I am working on I am required to use a class to write serialized data to a file, but all I have been presented with is the .jar file and a rather opaque usage example. Is there any way I can glean some information on it, such as inherited class and public methods?
You can unzip the jar using jar xf {jarname} and then use a decompiler on the relevant file(s). It won't give you the source, but you will get the structure, field names etc.
Your IDE should be able to tell you all this. Just create an instance of the class and type
inst. Ctrl+Space
You should now see a list of public fields and methods. If that doesn't work, try javap to dump the API of the class (there are also options to dump the byte code) or a Java decompiler like jad
Go to your java JDK directory (i.e C:\Dev\Java\jdk1.6.0_26\bin) use command jar xf "jar_name".
Than go to Download JAD and download decompiler. Then decompile classes from unziped jar.

Categories