Loading a Windows DLL in Java and initiate a class from it - java

I have a Windows DLL file from .NET, namely "System.Management.dll". I work with it using the code I write below:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_LogicalDisk WHERE Name = 'C:'");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Win32_LogicalDisk instance: ");
if (queryObj["VolumeSerialNumber"] != null)
{
Console.WriteLine("Drive Name : " + queryObj["Name"]);
Console.WriteLine("VolumeSerialNumber:", queryObj["VolumeSerialNumber"]);
SysdriveSerial = queryObj["VolumeSerialNumber"].ToString();
}
}
Now I need this piece of code to be in Java. So can I do this? Without anything like c++ unmanaged code. I don't want to use c++ unmanaged code to call to this dll.
I want something like this :
public class CallToCsharp {
private static native void ManagementObjectSearcher();
public static void main(String[] args) {
System.loadLibrary("System.Management");
System.out.println("Loaded");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_LogicalDisk WHERE Name = 'C:'");
}
}
Well this last code I have to put it in Java. How can I load this DLL and call the DLL to instantiate the native class in DLL and use its methods?
Update
I saw the thing, it seems it's a lot of work to do in case I have to use that class, like selecting each of them in .net Reflector and converting them to jar files. Now as per that tutorial I saw the jar files don't contain any real code to be used.
How to use it? I mean if I need to generate the jar file actually working with the code enough. How to go about it?
And aren't there any alternatives to this?

This is not an easy road you want to go down but IKVM might be able to help.
Overview
IKVM makes it possible to develop .NET applications using the Java language. Here's how it works:
Identify .NET classes you want to use in your application.
Identify which .NET dll's contain the .NET classes you identified in step 1.
Tip: If you're developing on Windows, the Microsoft .NET SDK Class Reference documentation
identifies the assembly / dll for a .NET class at the bottom of each class overview page.
Use the ikvmstub application to generate a Java jar file for each dll you identified in step 2.
The ikvmstub tool analyzes the .NET classes in the designated dll and generates a jar file
containing Java interfaces and stub classes. This information is needed by the Java source
compiler, which knows nothing about .NET assemblies.
Compile your Java source code using javac or jikes, with the ikvmstub-generated jar files on the
compiler classpath.
Compile the resulting Java classes using ikvmc. Use the -reference option to reference the dll's
containing the .NET classes you used; do not include the ikvmstub-generated jar files on the
compiler classpath.
For an example of this, see the tutorial.

Related

Can I run a subset of pure Java code from an Android project via a regular Java main method?

I have some code in an Android project that parses HTML using Jsoup. It doesn't use anything Android specific, they're just static methods that take an InputStream, and return my model classes. The app uses Gradle to build itself in Android Studio.
Is there any way I can create a standard Java main method to do something like load HTML from a local file, run it through my parser, and output a JSON file (using Gson on my model class)? I'm thinking maybe I can add a new sourceSet to Gradle like a jvmCompatible set of classes? I would greatly prefer not to copy my code to a separate project.
EDIT:
I guess I didn't make this clear, but I would like the be able to run this locally on my dev machine from the command line, rather than on an Android device or emulator.
You don't necessarily need to do anything in the build file to set this up; the build file generates Java .class files, and you can feed them to Java directly from the command line. You can add a main method to any class:
package com.example.foo;
class MyClass {
...
public static void main(String [] args) {
...
}
}
The main method will be happily ignored util you invoke it via the Java command line. You can do this by setting your classpath to the intermediate build directory and telling the Java command line which class to start:
java -classpath app/build/intermediates/classes/debug/ com.example.foo.MyClass
where you pass in the path to the build/intermediates/classes/debug directory in your app module's build output, and the fully-qualified name of the class.
Note that if you're running a release build that uses ProGuard, this main method could get stripped out if it's not otherwise referenced in the code.
Make sure you don't access any Android classes or you'll get a runtime error.
As an aside, you might find it worthwhile to separate out your Java-only code into a Java-only module in the build. Among other things, it would let you use JUnit to write nice test cases for the classes within; if you're asking this question because you want to do some testing of your parser, you might find it convenient to do so within the auspices of a unit test.

Requiring Java Classes in LuaJ

I'm attempting to make a game library in Java that uses Lua for the scripts. The real issue appears when I try to require a Java class (that is inside of a jar), and whenever I try to do so, I get an error much like the one below:
Exception in thread "main" org.luaj.vm2.LuaError: #/C:/xampp/htdocs/LevelDesigner/Projects/Lua Test/bin/levels/Test.lua:2 module
'resources.GameLevel' not found: resources.GameLevel
no field package.preload['resources.GameLevel']
How can I require a Java class that is within a jar? Right now it seems that, with Lua, I can only require .lua files, and not .class files. This is obviously problematic as Java files are compiled down to class files...And that is what I need to require.
The answer to this question is to use luajava.bindClass as opposed to require in all of your Lua scripts.

Accessing a Python object from Java Code in Jython 2.5

I have an application using Jython 2.1.
In the app I was using jythonc to convert the python scripts to java classes and then include these classes in my webapp like any other.
So I was able to assign package name to python scripts and access these classes like any other java class.
Now I plan to migrate to Jython 2.5. Jython 2.5 has removed support for jythonc.
So I tried to use
jython -m compileall /path/to/my/python/scripts.
When I do that I get all the compiled bytecode files in the same folder. Each of the files have names like myclass$py.class (where my python file is myclass.py).
My questions -
First of all can I access these classes in another normal java
class?
If so, what is the class name I should use ? When I use it like new
myclass() my code does not compile.
Is there a way, I can assign / force a package name or class name
for the generated bytecode with compileall?
Note -
I need to upgrade to jython 2.5 because I need newer versions of
python that it supports.
I would like to stick with pre-compiling the
python code into bytecode, as I want to do optimizations on the
bytecode. So the recommended object factory method is only a
last resort. I am assuming the object factory approach will not allow
me to process the generated bytecode.
Any help is appreciated.

Dynamically generating java class from a java program

At the build(compile) time of my project I need to do code-generation for a java class. The generated java class is a java bean class with a set of getters and setters. At the build time I am getting the name of the class and names of variables. So what I need to do is dynamically generate the java bean from the information which I have.
eg. At the compile time I am getting following data.
class-name=Test
variable-name=aaa
So the generate class should look like following.
public class Test {
public String aaa;
public void setVar(String str) {
this.aaa = str;
}
public String getVar(){
return this.aaa;
}
}
When I searched for a tool that I can use, I found Arch4j [1] interesting but the problem with that is it is not compatible with Apache 2.0 license. I am looking for a project/tool that is compatible with Apache 2.0 license.
I would appreciate if someone can give me some insight on how I can do this.
[1] - http://arch4j.sourceforge.net/components/generator/index.html
Why not just generate the .java file during your build, using a custom ant task or Maven plugin? This seems like a rather easy task which doesn't need any complex library. You could even use a template file with placeholders for the class name and the field name, and generate the real .java file using a replace task.
JET from Eclipse can be used:
http://eclipse.org/articles/Article-JET/jet_tutorial1.html
It can be called by ant: http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.jet.doc/references/ant/antTasks.xhtml
And I think from maven: http://mvnrepository.com/artifact/org.eclipse/jet/0.8.0-v20070605
Take a look at javax.tools package. You can create and load a dynamically generated class only with that package.
Just bear in mind you need the JDK available and that's not re-distributable so your customer would need to downloaded it separately ( just like you do in any IDE today )
http://download.oracle.com/javase/6/docs/api/javax/tools/package-summary.html
For instance, you can invoke the java compiler programatically with:
http://download.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html
And you can load it with URLClassLoader
Odd suggestion, but it seems like you want to generate beans. Why not use something like apache common's DynaBean? They allow you to create beans at run time. Here is an example of using DynaBean.
Of course this is at run time and not compile time. For compile time, I would recommend using an ant task to compile your source and add a dependency for compile on generation of your classes. You can handle the classes generation by writing a small java application that uses velocity as the java class template's engine.
So your ant task on compile first calls a small java program that generates the java class files using velocity template (delete the old files in ant if needed). Then compile as normal.

how to use a SWIG generated C++ class in a java program

I am successfully building a shared library that is C++ and loading it in my Java program with System.loadLibrary()
My class in the C++ file was called Classifier
How do I instantiate a new "Classifier" object in java? Do I have to compile and include the java files that are generated from Swig to do such a thing? If I do not want to do that, can I just use the methods from the class?
Used correctly, SWIG will have generated a wrapper Java class called "Classifier."
Yes, this needs to be compiled -- e.g., by including it in your IDE project and/or your build.
The SWIG documentation for Java shows how to instantiate a C++ object from Java:
C++ classes are wrapped by Java classes as well. For example, if you have this class,
class List {
public:
List();
~List();
void insert(char *item);
...
you can use it in Java like this:
List l = new List();
l.insert("Ale");
...
A few other thoughts:
You can ask SWIG to place the Java class in a package of your choosing, with the -package option on the SWIG command line.
I personally keep generated code in a separate source tree. You'll be periodically deleting it, and don't want to accidentally delete non-generated code.
If you do not need access to any C++ classes in your Java code, you might find JNA easier to work with than SWIG.

Categories