Java Implementation on IKVM-0.42.0.3. NET platform

Source: Internet
Author: User
IKVM is a Java implementation on Microsoft. NET Framework and Mono platform. It includes the following parts:
1. A Java Virtual Machine implemented with. NET
2. Java class library. NET implementation
3. Some tool sets for Java and. NET interoperability
IKVM provides two main methods to use Java projects on the. NET platform. One is the dynamic mode, that is, the JVM implemented through IKVM. NET runs Java projects directly. In this mode, the Java class or jar files need to be dynamically compiled into the. NET pencil,
Therefore, it is slow to start. The other method is static, that is, the IKVM tool is used to compile the class and jar files. NET, and then.. NET framework. NET Development
Java class library
For details about project components and assembly, refer to here:
1. ikvm.exe, which is applicable to the functions of java.exe and is used for dynamic running.
2. ikvmc.exe, which is applicable to javac.exe and used in static mode.
3. ikvmstub.exe: generate a Java class proxy file for the. NET Assembly to use the. NET Assembly function in Java.

This project is still very active, and has been developing and updating since. For purely JDK-based Java projects, IKVM should be able to handle well at present,
IKVM also supports Java projects that use Swing and JNI, but does not know the degree of support and stability.
IKVM is useful for 2: some projects in Java do not. NET implementation, and some Java open-source projects have corresponding. NET port, but Java projects are very active and constantly improving and updating. NET port is stuck
The lisence used by the project is worth considering. IKVM. OpenJDK. *. dll uses GPL V2, and other IKVM project files use lisence such as BSD.

Next we will use StringTemplate for a test.
JDK is required to be installed. Set the JAVA_HOME PATH (JDK directory) in the Windows environment variable. The PATH contains the JDK bin directory.
Download and install IKVM. This step is very simple. You only need to download the latest bin distribution from IKVM,
Decompress the package to a directory and add the bin directory of IKVM to the PATH of the system environment variable.

1. Java test project of StringTemplate
Download the latest Java StringTemplate from StringTemplate. If you download source for compilation, you can use Ant for compilation (the project contains the build. xml file ),
If Eclipse is used, apart from adding jar references of anlr, you also need to use anlr to generate lexical parser, syntax parser, token, and other related java files (A generated java file exists in the target \ generated-sources directory ),
Go to the src \ org \ anlr \ stringtemplate \ language directory. Compile the project and use Eclipse to export the stringtemplate jar file.
My version is antlr-2.7.7.jar, stringtemplate-3.2.1.jar
Create a test project with Eclipse, add antlr-2.7.7.jar, stringtemplate-3.2.1.jar reference, the java file used for testing is as follows:
Contact. java

Public class Contact {private String _ name; private String _ email; private int _ score;
Public Contact (String name, String email, int score) {this. _ name = name; this. _ email = email; this. _ score = score;} public String getName () {return this. _ name;} public String getEMail () {return this. _ email;} public int getScore () {return this. _ score;}/** StringTemplate does not support condition determination in the template. Therefore, attribute implementation */public Boolean getIsLevel3 () {return this is used in the model. _ score> 1000;} public Boolean getIsLevel2 () {return this. _ score> 200 & this. _ score <= 1000;} public Boolean getIsLevel1 () {return this. _ score <= 200 ;}}

Sttest. java

import java.util.Map;import java.util.HashMap;import java.util.ArrayList;import java.util.List;import org.antlr.stringtemplate.*;import org.antlr.stringtemplate.language.*;
public class sttest { public static void main(String[] args) { StringTemplateGroup group = new StringTemplateGroup("st-test" , "E:\\Richie\\java\\workspace\\StringTemplateTest\\lib\\st" , DefaultTemplateLexer.class); StringTemplate st = group.lookupTemplate("contact_list"); // a simple attribute st.setAttribute("simple_attribute", "Hello StringTemplate!"); // an object with properties as an attribute Contact c = new Contact("Richie", "Richie-test@gmail.com", 100); st.setAttribute("contact", c); // collections test for Map Map<String, Integer> map = new HashMap<String, Integer>(); map.put("key1", 111); map.put("key2", 222); map.put("key3", 333); st.setAttribute("items_hashtable", map); // collections test for Array int[] array = new int[3]; array[0]=1999; array[1]=2888; array[2]=3777; st.setAttribute("items_array", array); // collections test for List List<Contact> list = new ArrayList<Contact>(); list.add(new Contact("Jacky Pan", "JackyPan-test@gmail.com", 1608)); list.add(new Contact("RicCC", "RicCC-test@gmail.com", 180)); list.add(new Contact("Richie", "Richie-test@gmail.com", 682)); st.setAttribute("items_list", list);
System.out.println(st.toString()); }}

Directly compile it into the Contact. class and sttest. class files using Eclipse.
The StringTemplate file used for testing is as follows:
Contact_list.st

a simple attribute: $simple_attribute$$!this is a comment!$a contact instance:{ Name="$contact.Name$", EMail="$contact.EMail$" }Items - Map:$!     Remarks:     The following ST syntax for maps (.NET IDictionary implementations) is not supported     by StringTemplate C# port (Version 3.2)!$map.item_name: { key1 - $items_hashtable.key1$ },{ key3 - $items_hashtable.key3$ }iterator: $items_hashtable.keys: {{ $attr$ - $items_hashtable.(attr)$ }};separator=","$Items - Array:{ $items_array: {value|$value$};separator=","$ }Items - List:$items_list: row(seq="odd"), row(seq="even")$

Row. st

<tr class="list-$seq$">       <td>$attr.Name$</td>       <td>$attr.EMail$</td>       <td>$attr.score$</td>       <td>$if(attr.IsLevel3)$Diamond$elseif(attr.IsLevel2)$Golden$else$Standard$endif$</td></tr>$\n$$! Remarks: the previous instruction will yield a line feed !$

For convenience, create a IKVMTest directory, copy the antlr-2.7.7.jar, stringtemplate-3.2.1.jar, Contact. class, sttest. class files to the IKVMTest directory,
Create the st directory in IKVMTest and put it in the contact_list.st and row. st files.
Go to the IKVMTest directory on the command line and run the test project using java sttest. The result is as follows:

The implementation of StringTemplate C # is not perfect. The java test project above has two syntaxes. Currently, the StringTemplate C # version 3.2 does not support (or is a bug ),
One is the access method to the Map element (that is, the $ map_entry. (key) $ syntax), and the other is the $ elseif $ command, which may cause errors in many cases. I used the IKVM project to perform this test.

2. dynamically run Java Projects
Go to the IKVMTest directory on the command line and run the test project using ikvm sttest. the result is exactly the same as running with java.exe. We can also see that ikvm sttest has a high CPU usage for some time,
At this time, IKVM dynamically compiles the relevant class and jar files into the pencil code.
For usage of ikvm.exe, refer to here

3. Run the Java project in static mode
First, convert the antlr-2.7.7.jar to A. NET assembly
Ikvmc-out: antlr-2.7.7.dll-target: library-platform: x86 antlr-2.7.7.jar
Then convert the stringtemplate-3.2.1.jar into A. NET assembly. Because StringTemplate references anlr, the following command must use-reference to specify the dll file of anlr.
Ikvmc-out: stringtemplate-3.2.1.dll-target: library-platform: x86-reference: antlr-2.7.7.dll stringtemplate-3.2.1.jar
At the very end, convert contact.class‑sttest.classinto the. NET exefile sttest.exe
Ikvmc-out: sttest.exe-target: exe-platform: x86-reference: antlr-2.7.7.dll-reference: stringtemplate-3.2.1.dll-main: sttest Contact. class sttest. class
The above steps will generate three files in our test directory: antlr-2.7.7.dll1_stringtemplate-3.2.1.dll1_sttest.exe, which is the. NET hosted Assembly converted from jar and class.

When running a project converted from java in static mode, you need to reference some dll files related to IKVM. We can register the dll of IKVM to the global GAC, you can also copy the dll file to our test directory.
Here we directly go to the bin directory of IKVM and set IKVM. openJDK. beans. dll, IKVM. openJDK. charsets. dll, IKVM. openJDK. core. dll, IKVM. openJDK. security. dll, IKVM. openJDK. text. dll,
Running, you can see the running result and
The running results of java.exe are exactly the same.
For usage of ikvmc.exe, refer to here

4. Use Java projects in. NET
Next we will use Visual Studio to create a. NET test project to test the direct use of the StringTemplate converted from Java under. NET.
We manually port the java test project to the implementation of c. Create a Console project for IKVM. Test with Visual Studio, reference the antlr-2.7.7.dll,
Stringtemplate-3.2.1.dll these two files, reference IKVM. OpenJDK. Core. dll file, the project code is as follows:
Contact. cs

Namespace IKVM. Test {using System; public class Contact {private String _ name; private String _ email; private int _ score;
Public Contact (String name, String email, int score) {this. _ name = name; this. _ email = email; this. _ score = score;} public String getName () {return this. _ name;} public String getEMail () {return this. _ email;} public int getScore () {return this. _ score;} // StringTemplate does not support condition judgment in the template. Therefore, the following model uses attributes to implement public Boolean getIsLevel3 () {return this. _ score> 1000;} public Boolean getIsLevel2 () {return this. _ score> 200 & this. _ score <= 1000;} public Boolean getIsLevel1 () {return this. _ score <= 200 ;}}}

Program. cs

namespace IKVM.Test{    using System;    using org.antlr.stringtemplate;    using org.antlr.stringtemplate.language;    class Program    {        static void Main(string[] args)        {            StringTemplateGroup group = new StringTemplateGroup("st-test"                , ".\\st", typeof(DefaultTemplateLexer));            StringTemplate st = group.lookupTemplate("contact_list");            // a simple attribute            st.setAttribute("simple_attribute", "Hello StringTemplate!");            // an object with properties as an attribute            Contact c = new Contact("Richie", "Richie-test@gmail.com", 100);            st.setAttribute("contact", c);            // collections test for Map            java.util.Map map = new java.util.HashMap();            map.put("key1", 111);            map.put("key2", 222);            map.put("key3", 333);            st.setAttribute("items_hashtable", map);            // collections test for Array            int[] array = new int[3];            array[0] = 1999;            array[1] = 2888;            array[2] = 3777;            st.setAttribute("items_array", array);            // collections test for List            java.util.List list = new java.util.ArrayList();            list.add(new Contact("Jacky Pan", "JackyPan-test@gmail.com", 1608));            list.add(new Contact("RicCC", "RicCC-test@gmail.com", 180));            list.add(new Contact("Richie", "Richie-test@gmail.com", 682));            st.setAttribute("items_list", list);            Console.Write(st.toString());            Console.ReadKey();        }    }}

After compilation, ikvm.test.exebeibei is added to our test directory ikvmtest. the running result is still exactly the same as that of java.exe. We can see that the syntax not supported by StringTemplate C # can be correctly executed in this way.

Through the above. NET test project, we can find the following points:
1. Basic data types (such as string, int, and bool) are directly interconnected through IKVM
2. For the pencil project converted from java, java conventions must be followed for use in. NET.
For example, in the Contact class above, StringTemplate in java uses reflection to read attribute values. It uses the java convention to call methods such as getName () and getEMail ().
The same conventions must be used for reading. NET, but cannot be defined as. NET Property.
3. JDK class libraries must use IKVM. OpenJDK. Core and other IKVM implementations.
If we use IKVM in the project, we may need to use some encapsulation methods to separate the client's dependency on IKVM. For example, we can encapsulate the StringTemplate method through the interface,
Convert IDictionary to java. util. Map and IList to java. util. List to prevent clients from referencing such namespaces as java. util. In some cases, this separation may be annoying.

Performance Comparison
The st template used for performance testing and the Code for setting properties for StringTemplate are the same as the preceding code. The test result is
[Java version]: [C # version of StingTemplate]: [4. Use a Java project in. NET] = [1.5]: [1]: [16.2]
. NET's StringTemplate implementation has better performance than the java version. In. NET, the IKVM static method has a relatively high performance loss. IKVM has a certain performance loss, but this gap is too big. The results may be different for different projects.

Project files for trial use in the article: Download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.