Java on net platform

Consulo: Выполнение Java кода на .NET платформе с помощью IKVM.NET

Привет Хабр. Мои предыдущие посты описывают только поддержку Unity или Mono/Microsoft .NET. Но при есть ещё много вещей про которые я не рассказываю. Вот про одну я хочу рассказать, это IKVM.NET

Для тех кто пропустил мои посты:
Consulo — это форк IntelliJ IDEA Community Edition, который имеет поддержку .NET(C# на текущий момент, и на этот сектор пока идет большой акцент), Java

Представим ситуацию, что нам нужно запустить Java проект под IKVM.NET.

Начнем сначала с IKVM.NET

IKVM.NET is an implementation of Java for Mono and the Microsoft .NET Framework. It includes the following components:

A Java Virtual Machine implemented in .NET
A .NET implementation of the Java class libraries
Tools that enable Java and .NET interoperability

Найти больше про IKVM.NET можно здесь , читаем туториал но он скучный, и не сильно юзабелен для разрабоки.

Ставим нужные плагины для Consulo, нам нужны IKVM.NET + Microsoft .NET(Mono IKVM.NET не работает, проблема со стороны Xamarin) и их зависимости. В итоге наш список плагинов выглядит так:

image

.

Приступим. Создаем Java проект, и запускаем

image

Давайте посмотрим, что такое println:

image

Мы перешли на PrintStream.class который находится в rt.jar — все как обычно

Переходим на IKVM.NET

Теперь у нас ситуация — я не хочу терять поддержку JVM, но при этом я хочу иметь возможность запустить код под IKVM.NET. Копировать проект, или терять Java настройки, желания я не имею. Что нам делать?

Под другими IDE — таких как Visual Studio или IntelliJ IDEA, пришлось бы делать как выше описано — но не в Consulo. Consulo имеет функционал называем Module Layers, он позволяет создавать несколько слоев настроек для модулей, и при этом быстро переключатся между ними.

Стандартно — каждый модуль имеет один слой который имеет названия Default. .NET проекты создаются с двумя слоями Debug & Release

Заходим в настройки модуля, и делаем копию текущего слоя:

image

Называем его, например, IKVM:

image

Теперь мы имеем два слоя:

image

Мы имеем полную копию Default слоя, с поддержкой JavaExtensions включена Java)

Выключаем Java поддержки, и включаем IKVM.NET:

image

Java SDK нужно указывать, так как IKVM .NET не имеет встроенного компилятора Java кода, и используется javac.

Идем выше, настраиваем.NET расширения модуля:

image

Нам нужно включить Allow Source Roots, и выбрать Main TypeIKVM.NET не умеет выбирать Entry Point класс. Как видим, мы уже можем выбрать Java класс.

Также нам нужно, добавить в зависимости mscorlib.dll:

image

Если мы все правильно настроили, пробуем запустить уже существующий Run Configuration:

Читайте также:  Python peer to peer chat

image

Но это эмулирует поведения java.exe, и во время запуска транслирует JVM байткод в CLI, что гарантирует медленный запуск.

IKVM.NET предлагает компиляцию Java кода в *.exe файл, который потом запускается как обычное .NET приложения. Поэтому под IKVM.NET нам доступная другая Run Configuration, которая запускает .NET App:

image

image

Как видим, мы уже запускаем untitled1.exe а не ikvm.exe, скорость запуска намного выше :).

Пробуем перейти теперь на println:

image

Теперь мы видим что перешли в PrintStream.msil, который лежит в IKVM.OpenJDK.Core.dll. То есть мы работает уже с .NET байкодом, и можем например использовать .NET классы (все .NET классы имеет начальный namespace cli, что бы не конфликтовать с Java классами):

image

image

Теперь давайте вернемся на JVM реализацию:

image

image

Как видим — код красный, так как на JVM, .NET классы недоступные.

PS

Этот пост — показывает насколько гибкая поддержка, и не сосредоточена только на каком-то стеке технологий. IKVM.NET плагин много чего не умеет, ибо это не приоритетный плагин для меня.

В будущем хотелось бы увидеть Debug для Java кода на .NET платформе. Задача есть, и она глобальная — увы пока не решаема для меня.

Источник

Getting Started With JAVA (for .NET Developers)

Join the DZone community and get the full member experience.

Introduction

Every platform has its own weaknesses and strength and when selecting a platform you should off course also take into account the context of your organization and the goal that you want to achieve.

Please remember, there is no best language or platform. They are only fit for purpose.

The intention of this post is help you get started learning JAVA if you are a new programmer or if you used .NET/C# mostly in your carrier and are curious about trying java as well.

.NET v/s JAVA

C#/.NET are very similar to java. Like Java, C# & .NET are also open source.

.NET platform came 7 years after java but setup in similar way as java. Following are the main building blocks of .NET platform:

  • Programming Language (C#)
  • Standard Library
  • Runtime Environment (CLR , .NET equivalent of JVM).

Now if we look at building blocks of JAVA Platform:

  • Java Programming Language.
  • Java Standard Edition (Java SE) APIs (aka Standard library).
  • Java runtime environment (aka Java Virtual Machine).
    • JVM knows how to run byte-code that’s compiled from java source files and executed on the underlying hardware.

    Three parts of Java platform are bundled together in what’s called Java Development Kit (JDK).

    JDK is always starting point when you start developing java applications and it contains all the tools you need to create and run java applications. In next section, we will learn how to install JAVA.

    Install JDK

    When developing .NET applications, we install .NET SDK(s). On java side, we have JDK. Here are the steps to install it:

    • Download and install JDK
      • https://www.oracle.com/java/technologies/javase-downloads.html
      • Create an environment variable JAVA_Home and set Variablevalue.
      • Update Path for bin directory of Java.

      With Environment variable setup and Path updated, open command prompt and execution the >>java -version command to confirm that JDK installation is successful:

      Adapting JAVA

      Lets see the scalable development model offered by JAVA.

      • Hierarchical and structural code bases.
      • At the fundamental level, java starts with classes.
      • Related classes can grouped in packages.
      • Related packages yet again can be grouped into modules.

      In .NET, we have classes, namespaces, libraries etc. which offers similar capabilities.

      Productivity

      JAVA offers following capabilities out of the box:

      C# is also managed language so offers same benefits like java:

      Performance

      Following are few points towards performance characthersitics of JAVA:

      • Just-in-time compilation.
      • JVM specialized for underlying hardware.
      • With java, we have the platform-independent byte-code and a platform-specific JVM, giving both the benefit of portability and the benefit of performing highly specific optimization towards the actual CPU that the JVM is running on with just-in-time compilation.

      C# compiles to intermediate language (IL), which is similar to java byte-code. And .NET has CLR equivalent of JVM.

      Difference

      • C# moves much faster than java in terms of new features.
      • .NET stack recently move to cross-platform stack.

      Generally if a company have already invested in .NET eco-system then it will be logical to make a choice for C# and .NET. But if you want large eco-system of libraries and diversity then java is more logical choice.

      Demo: Compiling and Running Java Code

      In this very simple example, I used notepad to write a java program:

      We can use java compiler javac to compile this program. This will output byte-code (Hello.class) file.

      Now to run byte-code, we will use this generated class >> java Hello(.class is default).

      Congratulation, you just wrote your first java program, compile it and then execute it. You can download the code on this git repo.

      Typically, you will use an IDE for development purposes and an IDE will simplify this process greatly. You can use IntelliJ IDEA which has a free community version available or you can use Visual Studio Code or any other IDE which you like more. Eclipse, NetBeans are also popular for java development.

      JAVA in Visual Studio Code

      You can setup visual studio code for java development very easily. You can install Coding Pack for Java from this link:

      Once, this is installed, open the project folder in VS-Code and Run the application to see the results:

      Summary

      In this post, we saw a very simple comparison b/w java and .NET and focus was mostly towards similarities. I think if you try to map your existing C# skills to java then it will make it easier to learn and program JAVA. As both platforms are very similar and their syntax is also not very different, this makes it easier even more. If you have some questions or comments, feel free to reach out to me. Till next time, Happy Coding.

      Published at DZone with permission of Jawad Hasan Shani . See the original article here.

      Opinions expressed by DZone contributors are their own.

      Источник

      Java on net platform

      Tagged as

      Stats

      Comments and Discussions

      Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\****\oojnidotnet.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform

      Thanks for reply I know that, and this file are in the same directory and it’s works fine when I use the the CSharpInJava.dll that is uploaded in this article; but when I replace CSharpInJava.dll(that uploaded here) with another CSharpInJava.dll(that I create from source code here) I get unsatisfied link error!

      Thanks a lot for this very nice sample.
      I’m having some problems passing arguments when calling a Java method from C#.

      Thats the way i call the Method:

       
      JClass cls = JNIEnvHelper.GetObjectClass(new JObject(obj));
      int fid = JNIEnvHelper.GetStaticMethodID(cls, "TestCall", "()I");
      JNIEnvHelper.CallStaticIntMethod(cls, fid, myObject);

      If i leave the «TestCall» Method in Java without arguments, than its working. But how can i get the Values from the Object «myObject»?

       
      public static int TestCall( ?? ?? :confused:)< /* do some stuff */>

      public static int TestCall()< /* do some stuff */>
      JClass cls = JNIEnvHelper.GetObjectClass(new JObject(obj)); int fid = JNIEnvHelper.GetStaticMethodID(cls, "TestCall", "()I"); NIEnvHelper.CallStaticIntMethod(cls, fid, myObject);

      in this case TestCall should have one parameter, for example,

      public static int TestCall(Object o)< /* do some stuff */>
      JClass cls = JNIEnvHelper.GetObjectClass(new JObject(obj)); int fid = JNIEnvHelper.GetStaticMethodID(cls, "TestCall", "(Ljava/lang/Object;)I"); JNIEnvHelper.CallStaticIntMethod(cls, fid, myObject);
      public static int TestCall()< /* do some stuff */>
      . JClass cls = JNIEnvHelper.GetObjectClass(new JObject(obj)); int fid = JNIEnvHelper.GetStaticMethodID(cls, "TestCall", "()I"); JNIEnvHelper.CallStaticIntMethod(cls, fid);

      Thanks for your quick reply.
      Its now working as expected!

      JNIEnvHelper.CallStaticIntMethod(cls, fid)

      What about a native method implementation in .NET code (C#, J#, VB# do not support export functions), Java interfaces implementation with .NET classes?
      P/Invoke I use only in OOJNI Add-In for MS VS 8.0/9.0 (written in C#) while parsing Java bytecode.

      #
      # An unexpected error has been detected by HotSpot Virtual Machine:
      #
      # Internal Error (0xe0434f4d), pid=2924, tid=3224
      #
      # Java VM: Java HotSpot(TM) Client VM (1.5.0_06-b05 mixed mode)
      # Problematic frame:
      # C [kernel32.dll+0x12a5b]
      #

      Is there already some oojni for WPF and VS2008?
      Is there another way of using WPF UserControls in Java (swing)?

      That’s good news! I guess you currently don’t know when such thing would be available, right?

      I was also thinking to go through a COM layer using JNI.
      Do you know if this would be feasible?
      Thanks

      Hope you take this initialtive.

      General News Suggestion Question Bug Answer Joke Praise Rant Admin

      Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

      Источник

Оцените статью