I am trying to compare JVM Bytecode and Java as programming languages.
Can you think of any example Bytecode class that could not be rewritten in Java, not even when using lots of (Java-) Boilerplate code? Maybe any construct that other JVM languages like Scala use?
[Edit]
I am not talking about a comparison of instructions or the possibility to create a certain algorithm. Let me rephrase the question: "Could there be any 'pattern' that another JVM language could use but Java doesn't?".
[/Edit]
[Edit2]
Maybe it's easier if I explain what this question really is about. I am working with a source code transformation system, and asked myself the question if there is any pattern or construct that might be useful but cannot be added to a Java class just by transforming plain Java code but requires modification of the Bytecode itself.
[/Edit2]
In Java you cannot have two methods with the same names that differ only with return type - Java Bytecode allows to do that
Bytecode allows to create instance of class without calling constructor
Bytecode allows to directly use GOTO, which isn't allowed in plain Java
Update: Simillar question has been answered here
Also I want to add that you cannot use type information at runtime. So if you wanted to transform C#, which keeps generic information at runtime, to JVM bytecode, you cannot do it 1:1. Type erasure: Java vs C#
Related
I have a large programme written in C++ that needs to use a specific Java library. Ideally I would like to create an equivalent C++ library that wraps this existing Java code. As such I have been looking into the JNI invocation API.
Since I am not a very experienced programmer, and I am also inexperienced with JNI and multi-language programming, I would greatly appreciate some general pointers/tips/advice as to how to tackle this problem.
Things I would be especially interested to know:
Should each Java class in the Java lib map to to an associated C++
class? I.e. in my C++ library, will I have a class each invoking a
JVM for a particular Java class? Or will I have a singular JVM through which everything is accessed? What is the best way to do this and why?
What will be the basic process and architecture for doing this?
Are there any specific resources for creating a C++ lib from Java lib using the invocation API?
Thanks a lot!
I've done this before, but it's not for the faint-hearted especially if your interface between the 2 languages is hard. Debugging can also be a pain in this situation.
To answer your points:
You should start by deciding on what functionality from the Java library you need to access in your C++ program. Is it just a few tasks? Try making a very simple interface from C++ to Java in this case. Is it complicated? Then you're gonna have to start mapping Java classes to C++, and the more you need then the more work it's gonna be.
The end of q1 is sorta q2 really. Your C++ program will start a single JVM which will run as part of your program. When you make calls across the C++ data will be transferred into the JVM, and then the Java code executed, and then the return values transferred back. This incurs a performance cost so calling small functions like add(int,int) through JNI would be more expensive than just doing it in C++.
There's a lot of basic guides you can Google to get started. Just managing to start a basic JVM from C++ and making a call is actually a bit of work since you need to get the paths to the JVM libs correct or it doesn't work (unless they've improved this, it's been years since I tried). So you might want to check that out first before asking more specific questions about JNI and mapping functions.
An alternative option (which may or may-not be possible depending on your library and use-case) is to just write some kind of wrapper service around your library, actually in Java. And then send requests to it via JSON-HTTP or some messaging system.
An even-more alternative option, rewrite whatever the library is doing in C++.
You can use scapix::link::java C++ JNI library to generate C++ headers for any Java code, then easily access this Java code from C++. Here is an example:
#include <scapix/java_api/java/lang/System.h>
#include <scapix/java_api/java/util/Locale.h>
#include <scapix/java_api/java/text/DateFormatSymbols.h>
using namespace scapix::link::java;
using namespace scapix::java_api;
void test1()
{
// C++ objects are automatically converted to and from corresponding Java types.
// This works for any type supported by scapix::link::java::convert() interface,
// which supports many STL types and can be extended for your own types.
std::string version = java::lang::System::getProperty("java.version");
std::vector<std::string> languages = java::util::Locale::getISOLanguages();
std::vector<std::vector<std::string>> zone_strings = java::text::DateFormatSymbols::getInstance()->getZoneStrings();
std::map<std::string, std::string> properties = java::lang::System::getProperties();
}
Can we create a class in say C# which can be used in other high-level languages like Java.?
To be more specific say, I have defined a function in c#. Now can I use the same function in other languages like Java without re-writing it and by using reference or anything else to the class in c# ?
The question here is not strictly limited to any particular language? Question here is that Can we create a class in one language which can be used in other language.
Can we create a class in say C# which can be used in other high-level
languages like Java.?
NOPE.
Yes you can use such a construct. A web service is language independent or you can call(a executable programme) with a cmd command.
OP:
Can we create a class in say C# which can be used in other high-level languages like Java.?
I have defined a function in c#. Now can I use the same function in other languages like Java without re-writing it
Yes it can be done.
You can generate Java proxy classes for invoking c# by using the tool jni4net.
bridge between Java and .NET (intraprocess, fast, object oriented, open-source)
This is what they have to say on the tool:
Using reflection we grab public method signatures for core classes of .NET and Java and generated proxy classes for the other side.
We have .NET version of JNI API.
We use JNI to forward the call from .NET proxies to methods on real Java objects. (explanation)
We use JNI to register .NET implementation of native methods of Java proxies to forward call to methods on real .NET objects More...
Source and binaries are available here
But wait there's more!
Though not a requirement, you can use jni4net to call Java from .NET.
See also
How calling from Java to .NET works in jni4net
Generally spoken: No
As some answers stated: For many languages there is a way of invoking methods/functionality of compiled compiler-output, but IMO the only szenarios I can think of it beeing useful is when it comes to legacy-software or not language-independent APIs (eg. not using rest). An Example could be calling a Method of a legacy-C#-class from a Java program for the sake of downward comnpatibility or because it was meant to work with .NET only. But you must be aware that there is no general approach of doing that which would work for any language-combination and IMO this is not using a class/method, its just invoking it.
When it comes to green-field projects, I would avoid using (to many) different languages (polyglot-programming). Maintainability suffers heaviliy because Developers need to know all used languages, use different IDEs etc. Also, debugging becomes a pain.
Using the same language for different parts of a system has the huge advantage of beeing able to use classes of some kind of shared libraries which are developed/tested independently.
However: if you are forced to use different languages for some reason, I would suggest to try and recreate the required shared functionality twice for each language (it sucks I know) and pass objects around by (de-)serializing them. This way, your projects remain testable and debuggable.
Is there any way to create native function from jni without creating dll? I mean like in python http://docs.python.org/2/extending/embedding.html
Section 5.4. Extending Embedded Python
I don't want to use dll exported functions.
Regards
You can embbed VM in a native application, call into Java from C/C++ then callback from Java back into C/C++. See the Invocation API in JNI documentation. This way there is no need for dynamic linking (DLLs). You can also dynamically generate classes in runtime by generating bytecode with native methods (e.g. with ASM) and then registering whatever C/C++ function pointers you need with RegisterNatives.
technically it is possible.
Around 6 or 8 years ago I saw a C++ implementation (it was at codeproject site presented), which created a JVM and did access Java classes. Isn't very popular, for very good reasons, are to many to enumerate here, but is possible.
I would strongly recommend to do the other side, exactly what you don't want: java invoke the dll or so, but to many reasons, but is up to you...
Perhaps JNA does what you want?
Are there any programs out there that will convert Java code to C++?
Java is a completely different language to C++. The code will probably have to be completely rewritten from scratch. Even if there is a Java to C++ compiler:
It wouldn't work on all Java code.
It would not write code that looks like it is written by a C++ programmer.
It would probably not use the ordinary C++ or STL types so even if it is valid C++ it wouldn't integrate well with any other code.
You can compile some Java code to native code. Maybe that would be a better approach for you.
I've used this utility with basic projects:
http://www.euclideanspace.com/software/language/xes/userGuide/convert/javaToCpp/index.htm
erotsppa - i wasn't aware of any until browsing this question. we had researched some java to c# tools a few years back with varied success.
anyway, a google search (which i'm sure you've done) turned up a few interesting results:
http://www.euclideanspace.com/software/language/xes/userGuide/convert/javaToCpp/index.htm
http://www.scicontrols.com/R2J.htm
jim
There could be potentially.
But the styles of the two languages are so different that the resulting C++ code would look very none C++ like and as such would be hard to maintain.
The real question is why yuo are trying to do this?
There's the JC Virtual Machine which translates Java bytecode to C, which is compiled and run:
http://jcvm.sourceforge.net/
If you just want to use a Java library in a C++ application (or vice versa), then you should consider gcj from the GNU compiler collection instead. It's a java->native code compiler. The C++ compiler has specific extensions to interoperate with the code compiled with gcj, which means you can basically use a module written in Java as if it was written in C++.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am a Java developer and I want to know how I can use Scala in my Java programs?
Go read Daniel Spiewak's excellent blog series about Scala. With Scala you can keep:
all your Java libraries
all the advantages of running on a JVM (ubiquity, administrative tools, profiling, garbage collection etc)
But you can write Scala code:
more concise and clear than Java (especially using more functional style, such as in the collections library)
it has closures and functions as part of the language
it has operator overloading (from the perspective of usage)
it has mixins (i.e. interfaces which contain implementation)
Also, take a look at this recent news item post on Scala's site:
"Research: Programming Style and Productivity".
In his paper, Gilles Dubochet, describes how he investigated two aspects of programming style using eye movement tracking. He found that it is, on average, 30% faster to comprehend algorithms that use for-comprehensions and maps, as in Scala, rather than those with the iterative while-loops of Java.
And another key quote from the news item:
Alex McGuire, who writes mission critical projects in Scala for power trading companies, says of Scala "The conciseness means I can see more of a program on one screen. You can get a much better overview. When I have some mathematical model to write with Java I have to keep two models in my head, the mathematical model itself and the second a model of how to implement it in Java. With Scala one model, the mathematical one, will do. Much more productive.”
You an read the rest of the post and other linked items there.
UPDATED 2019
I can name some simple points in plain language from my limited experience:
Properties. C++ and Java had this notion of a public getter/setter function "property" wrapped around an internal class variable which led to large amounts of boilerplate code. C# formalized this as a real language feature and reduced much of the boilerplate in C# 3.0 with auto-implemented properties. Scala classes define trivial properties simply as regular read only vals or read/write vars. The class may later choose to replace those with get or get/set methods without affecting client code. For this, Scala provides the most elegant solution with the least language features and complexity.
Arrays use regular generics. In Java/C#, int[] is redundant and confusing vs List<int> or List<Int>. Worse, in Java, List<Int> has lots of runtime overhead, so many developers have to know to use int[]. Scala avoids that problem. Also, in Java/C#, arrays support (covariant) casting, which was a mistake, that they now can't fix because of legacy concerns.
Scala has better support for immutability. val is a basic language feature.
Scala lets if blocks, for-yield loops, and code in braces return a value. This is very elegant in many situations. A very small plus is that this eliminates the need for a separate ternary operator.
Scala has singleton objects rather than C++/Java/C# class static. This is a cleaner solution.
Pattern matching. Object unpacking. Very nice in a large numbers of situations.
Native tuples.
"case classes" which are what most other languages would call record types or named tuples.
Fancier standard library with more elegant collections.
Multi-line strings. String interpolation formatting.
Optional semi-colons.
Cons.
Java has caught up a lot. Java 8 was first released in 2014, but it took several years for older Java versions to be phased out and the new Java 8 features to be fully used across the Java ecosystem. Now, lambdas and closures and basic functional collections, with support for filter/map/fold are quite standard for the Java ecosystem. More recently, Java has added basic var local variable type inference and has multi-line strings and switch expressions in release builds preview mode.
Scala is complicated. I'd highlight features like implicits to be inherently confusing.
Scala has minimal backward compatibility. Scala 2.10 artifacts are incompatible with Scala 2.11.
Building a Java API for other JVM-language developers like Scala or Clojure or Kotlin is normal, well supported and accepted. You generally don't want to build APIs in Scala that cater to non-Scala developers.
I am not sure you can easily use Scala in your Java programs, as in "call a Scala class from a Java class".
You can try, following the article "Mixing Java and Scala".
Relevant extracts:
The problem is that the Java and Scala compilation steps are separate: you can't compile both Java and Scala files in one go.
If none of your Java files reference any Scala classes you can first compile all your Java classes, then compile your Scala classes.
Or, if none of your Scala files reference any Java classes you can do it the other way around.
But if you want your Java classes to have access to your Scala classes and also have Scala classes have access to your Java classes, that's a problem.
Scala code can easily call directly into Java code, but sometimes calling Scala code from Java code is trickier, since the translation from Scala into bytecode is not quite as straightforward as for Java:
sometimes the Scala compiler adds characters to symbols or makes other changes that must be explicitly handled when calling from Java.
But a Scala class can implement a Java interface, and an instance of that class can be passed to a Java method expecting an instance of the interface.
The Java class then calls the interface methods on that instance exactly as if it were a Java class instance.
The opposite is possible, of course, as described in Roundup: Scala for Java Refugees, from Daniel Spiewak.
Scala or Java:
Pros:
Scala supports both functional and imperative OO programming styles and it advocates that both models are not conflicting with each other but yet they are orthogonal and can complement each other. Scala doesn't require or force the programmer to use a particular style, but usually the standard is to use functional style with immutable variables when appropriate (there are several benefits of using the functional approach such as concise and short syntax and using pure functions usually reduces the amount of non-determinism and side-effects from the code), while resorting to imperative programming when the code would look simpler or more understandable.
Scala doesn't require ; at the end of each line having it optional which leads to cleaner code
In Scala functions are first class cititzens
Scala supports some advanced features which are directly built in the language such as: Currying, Closures, Higher order functions, pattern matching, Higher Kinded Types, Monads, implicit params.
Scala can interact very well with Java and both can coexist. It is possible to use java libraries directly inside Scala code invoking Java classes from scala code.
Has Tuples built in the language which makes life easier in several scenarios
Supports operator overloading
has a rich Ecosystem and some popular open source projects in Apache are based on it.
Async and Non-blocking code is very easy to write with Scala Futures
Scala supports the Actor model using Akka which can be highly efficient and scalable when running distributed applications in multi-threaded and parallel business use cases (Enforce encapsulation without resorting to locks, State of actors is local and not shared, changes and data is propagated via message)
Code tends to be shorter if compared to Java (might not be always the case)
Cons:
Steep learning curve if compared to Java and other languages, requires more time in general from the learner to understand all the concepts clearly. Has many features
It is not as well established as Java in the market since it was invented later so Java in overall is more mature and more battle-tested.
Scala opens too many doors. It allows a lot of complex syntax that if used in a irresponsible way might lead to code that is hard to understand.
Abusing things such as operator overloading, implicit params and other constructs can be counter-productive and might ruin code legibility.
Java is also evolving and still getting better with newer versions (such as with JDK 9 modules)