I am quite a newbie to Clojure. I am trying to build my computational units (pure functions) in Clojure and bind all these functions into a program using Java.
For accessing Clojure in Java, I have done one thing i.e. Ahead-of-time compilation and class generation. But it looks cumbersome and weakens the idea of using Clojure into my application. So my question is have anyone tried to access Clojure functions in Java (excluding class generation and AOT compilation)? If not, then how to interlink these computational units (or Clojure functions) into a program (where there are several methods interlinked with each other) using purely Clojure?
Just as an overview the general process is:
include the clojure runtime:
import clojure.lang.RT;
use the runtime to load your namespace (which will compile it):
RT.loadResourceScript("path/core.clj");
get the iFn Object for the function you would like to call:
RT.var("mynamespace.core", "main")
and call the invoke method on that object
Have a look at my clojure-utils library. There are a lot of handy tools here for calling Clojure code from Java.
Here's a trivial demonstration:
import mikera.cljutils.Clojure;
public class DemoApp {
public static void main(String [] args) {
String s = "(+ 1 2)";
System.out.println("Evaluating Clojure code: "+s);
Object result=Clojure.eval(s);
System.out.println("=> "+ result);
}
}
I prefer to avoid AOT compilation: instead use the utilities in mikera.cljutils.Clojure to load, compile and execute Clojure code dynamically at runtime.
Related
I know there are other questions like this, but they do not answer my question.
in C#, you would use:
using System;
namespace Program
{
static void Main(string[] args)
{
Console.WriteLine("Helllo, World);
Console.ReadLine();
}
}
You use using System; from having to do this:
namespace Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Helllo, World);
System.Console.ReadLine();
}
}
In Java, is there an equivalent to C#'s using System;?
The comments are addressing why the communities of these languages have settled on different approaches, but to answer the question directly:
In Java, the import statement allows for a * suffix to indicate that all classes from a namespace should be imported and usable within the current file without any prefix:
import java.util.*;
This is basically equivalent to something like
using System.Collections.Generic;
However, the Java standard library and the C# standard library are organized quite differently, so there is no declaration that is exactly the same as C#'s using System.
In Java, however, the java.lang package is always implicitly imported, and java.lang contains many things that would be in C#'s System, so you could say that Java makes using System implicit!
For example, in C#, you need using System; to be able to write Console.WriteLine("Hello, World!");, but in Java, you don't need import java.lang.System; to be able to write System.out.println("Hello, world!");.
Java also has a feature called import static, where you can import members of a class rather than just the class itself or the classes in a package. So you could do something like import static java.lang.System.out; or import static java.lang.System.*; and then write out.println("Hello, world!"); if you prefer.
C# also has a feature called a namespace alias where you can import a single name from another namespace, optionally renaming it as you go. So you could write using C = System.Console; and then write C.WriteLine("Hello, world!"); if you prefer.
Both of these latter options are not commonly used with the standard library, but might be used in special cases, or with special classes that are designed to be used in such a way.
Addendum about:
... but then why do C# users use using statements?
Simple: because they only have using, and not Java import. It is a build in property of that language, similar to the fact that C# supports the .Net platform, and Java (mainly) supports the JVM platform.
In other words: different languages follow different paradigms and concepts, very much like "real" human languages. Thus, in essence, the question why does language A support feature X, but language B has Y are (often, not always) not leading to much else but "because that is what the individual people wanted to have".
I have a module written in Scala that I need to integrate into a Java web application. Everything works great, except the fact that methods and fields that are
private[somepackage]
in the Scala classes appear to be accessible from the Java code from outside that package. Is there any way to hide those?
EDIT: example illustrating what is happening
package my.scala.module
class SomeClass {
private[scala] val myValue = "this should be hidden"
}
package com.something.service;
import my.scala.module.SomeClass;
public class MyService {
private static SomeClass someInstance = new SomeClass();
public static void main(String[] args){
System.out.println(someInstance.myValue());
}
}
Running main will cause "this should be hidden" to print
There is no way to encode this constraint in JVM bytecode. It is enforced by the Scala compiler, but neither the JVM nor Java know anything about it.
There are some Scala features which can be encoded in JVM bytecode, and some which can't.
In particular, there are some constraints which cannot be encoded in JVM bytecode, e.g. sealed or private[foo], or val. Which means that if you get your hands on the compiled JVM bytecode of a Scala source file, then you can do stuff that you can't do from Scala by interacting with the code through a language that is not Scala.
This is not specific to the JVM backend, you have similar, and even more pronounced problems with Scala.js, since the compilation target here (ECMAScript) offers even less ways of expressing constraints than JVM bytecode does.
But really, this is just a general problem: I can take a language as safe and pure as Haskell, compile it to native code, and if I get my hands on the compiled binary, all safety will be lost. In fact, most Haskell compilers perform (almost) complete type erasure, so there are literally no types, and no type constraints left after compilation.
Similar to dynamic SQL, wherein a String is executed as an SQL at runtime, can we have Java code run dynamically? Like I return a String which is a Java code and then I execute at runtime. Is this possible?
For real Java code, this is possible using the JavaCompiler interface. However, it's very inconvenient to use since it's just an interface to a real Java compiler that expects to compile entire class definitions found in files.
The easiest way to execute code supplied at runtime would be to use the Rhino JavaScript engine.
Both of these options have been only in Java 6, though I believe the scripting interface existed before, so you could use Rhino in an earlier JRE if you download and add it to the classpath.
Javassist
You would need to use a bytecode manipulation library such as Javassist (Wikipedia), in order to run an arbitrary string that is provided at runtime. Javassist allows you to create a CtClass based on a string representing source code; and can then turn this into compiled Class object via a particular classloader, so that the class is then available to your application. Other libraries would need to do something similar to these two steps in order to achieve the same thing.
So it is possible, but it's very heavyweight and is likely to make your application very hard to reason about. If at all possible, consider designing a very flexible class statically, and having it accept parameters that control its behaviour.
If you want to do more than invoke an existing method dynamically, you may need to compile your String into bytecode. An easy way to do this is to include the Eclipse/JDT compiler jar in your classpath, and then you can use that to compile your String into a Class, which can then be loaded.
This type of dynamic code generation and execution is used to convert JSP files into Servlets and is used in other packages such as JasperReports to turn a report specification into a Class that is then invoked.
Remember that just as with SQL you must be careful to prevent code injection security problems if any of the String contains user-specified data.
You also may want to look at Java 6 scripting support:
http://download.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.htm
Here is a version of hello world that creates array of strings and prints a first one:
import javax.script.*;
public class EvalScript {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval("var a=java.lang.reflect.Array.newInstance(java.lang.String, 1);a[0]='Hello World';print(a[0])");
}
}
Yes it is possible. Look at the Java Compiler API. Have a look here:
http://download.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html
Have a look at Beanshell. It provides an interpreter with java like syntax.
I want to have one feature of Java 8 for Java 7: automatic interface implementation generation for method (to avoid performace deficiency due to reflection calls). I know that Java 8 provide the generation at compile time but I think it's not possible for Java 7 (without maintainance of metadata files). So I agree with implementation generation at runtime.
Example:
I have following interface:
public interface Extractor<E> {
public Object getProperty(E aSourceObject);
}
And a bean class (or interface)
public class Foo {
public int getProperty1();
public String getProperty2();
public boolean getProperty3();
}
I need for each property of Foo an implementation of Extractor interface. Something like Foo::getProperty1 for Java 8.
public class Foo1Extractor implements Extractor<Foo> {
public Object getProperty(Foo anObject) {
return anObject.getProperty1();
}
}
Should I use JavaCompiler (currently I have few interfaces to implement and can work with template classes) or you have better solutions?
The main requirement is the short bytecode generation time and LGPL compatibility (can be used in commercial product).
If possible, provide a little example for my case.
You may not see visible performance improvement if you replace reflection with generated classes unless your application is performing millions operation per second. Also the complexity of adding the dynamic code generation to the project (both in runtime and compile time) are quite high. So I'd recommend to go for it only if reflection is proved to be the real bottleneck.
Anyway, for the code generation in compile time in JDK 7 you can the use the annotation processing API, which is basically a plugin API for javac that you can combine it with some sort of template engine. Have a look at this project which uses the power of the annotation processing for doing quite good stuff.
Similar to dynamic SQL, wherein a String is executed as an SQL at runtime, can we have Java code run dynamically? Like I return a String which is a Java code and then I execute at runtime. Is this possible?
For real Java code, this is possible using the JavaCompiler interface. However, it's very inconvenient to use since it's just an interface to a real Java compiler that expects to compile entire class definitions found in files.
The easiest way to execute code supplied at runtime would be to use the Rhino JavaScript engine.
Both of these options have been only in Java 6, though I believe the scripting interface existed before, so you could use Rhino in an earlier JRE if you download and add it to the classpath.
Javassist
You would need to use a bytecode manipulation library such as Javassist (Wikipedia), in order to run an arbitrary string that is provided at runtime. Javassist allows you to create a CtClass based on a string representing source code; and can then turn this into compiled Class object via a particular classloader, so that the class is then available to your application. Other libraries would need to do something similar to these two steps in order to achieve the same thing.
So it is possible, but it's very heavyweight and is likely to make your application very hard to reason about. If at all possible, consider designing a very flexible class statically, and having it accept parameters that control its behaviour.
If you want to do more than invoke an existing method dynamically, you may need to compile your String into bytecode. An easy way to do this is to include the Eclipse/JDT compiler jar in your classpath, and then you can use that to compile your String into a Class, which can then be loaded.
This type of dynamic code generation and execution is used to convert JSP files into Servlets and is used in other packages such as JasperReports to turn a report specification into a Class that is then invoked.
Remember that just as with SQL you must be careful to prevent code injection security problems if any of the String contains user-specified data.
You also may want to look at Java 6 scripting support:
http://download.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.htm
Here is a version of hello world that creates array of strings and prints a first one:
import javax.script.*;
public class EvalScript {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval("var a=java.lang.reflect.Array.newInstance(java.lang.String, 1);a[0]='Hello World';print(a[0])");
}
}
Yes it is possible. Look at the Java Compiler API. Have a look here:
http://download.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html
Have a look at Beanshell. It provides an interpreter with java like syntax.