In my java code, I am calling a method, from a class which is defined in Scala, and I want to use one of its methods in java. Here is how I call it and it works fine.
Seq<SomeObjectType> variableName = ScalaClass.MethodInTheScalaClass();
I can call this function in java in this form, but since I am calling this method from a compiled package, I can't see what it going on (and therefore I can't change it).
The problem now is that, I don't know how to iterate over the "variableName" in java (since Seq is a scala type).
How can I iterate over variableName or convert it to a Java object (e.g. List)?
Try this:
java.util.List<SomeObjectType> res =
scala.collection.JavaConverters$.MODULE$.seqAsJavaListConverter(variableName).asJava();
You could get converters list in JavaConverters documentation.
You should use JavaConverters$.MODULE$ to get JavaConverters object from Java.
Related
i have been working on converting a python code to java which is related to my research work. i just cannot understand how to convert python type "any" to java, as we dont need to write data types in python but in java its necessary. i need your kind suggestions on that
i am trying to read data from a file and putting it into different lists, as python can automatically handle the datatypes of that data, is there any similar method to do it in java.
covMatrix = savedata[1]
covMatrix and savedata both have inferred type any at initial stage, i want to write it in java but there i have to write the data type. as i told you i want to know that is there any method in java to automatically detect the data type of data.
I think in Java 10 you can use the var keyword to get local variable type inference. I've never had to use it personally though so I'm not sure how you would go about using it in your context. Hopefully this gets you moving in the right direction though.
Have a look at this question, as it may direct you to a solution you're looking for. Is there auto type inferring in Java?
Use the var identifier, it infers the type for you.
var covMatrix = savedata[1];
Note that it only appeared in Java 10, so if you are using an older version of Java it's not possible to infer the type and you have to write it manually.
You can use Object, it is basically Java's Any
e.g. Object covMatrix = savedata[1];
Why do all scala vararg methods, when used from java, seem to accept a Seq of variables, and can't be used as java native vararg methods. Is this a bug?
For instance, Buffer has method def append(elems: A*): Unit. But in java it has another signature: void append(Seq<A>).
If you control the scala code you can use #varargs to make it generate a java-compatible varags method, e.g. #varargs def append(elems: A*): Unit = {}
It is not a bug. It is a design choice that favors vararg use within Scala over interoperability with Java. For example, it allows you to pass a List into a Scala varargs method without having to convert it to an Array on the way.
If you need to use Scala varargs from Java, you should create some scala Seq instead. You can, for example, write a Java wrapper to get an array automatically created, and then use the genericWrapArray method from the Predef object.
you can easily cast a Seq in varargs using :_*. For example :
val b = collection.mutable.ListBuffer.empty[Int]
b.append(List(1, 2):_*)
so this avoid code duplication in the collection API.
You can also simply use appendAll :
b.appendAll((List(1, 2))
Is there an easy way to get an arbitrary Function version of a method on a POJO?
For example:
FluentIterable.from(myCollection).uniqueIndex(Functions.for(Item.class).getId)
.first(Predicates.equalTo(id)).get();
Where Functions.for ideally behaves like Mockito.mock
Actually you can use lambdaj which is
a library that makes easier to address this issue by allowing to
manipulate collections in a pseudo-functional and statically typed
way.
Lambdaj does similar tricks as Mockito, so you should read its limitations (most important is that your POJO must not be final).
With lambdaj, your code could be something like this (note that uniqueIndex from your example returns Map, which does not have first method, so I'll guess here):
import ch.lambdaj.Lambda.*; // for all static methods used below
// just items indexed by their ids
Map<Intgeger, Item> indexed = index(myCollection, on(Item.class).getId());
// or more likely you want
Item foundItem = selectFirst(
myCollection, having(on(Item.class).getId(), equalTo(id)));
That's not how Java works.
However, with Java 8, you can use a method reference to create a lambda:
FluentIterable.from(myCollection).uniqueIndex(Item::getId)
.first(Predicates.equalTo(id)).get();
I have a .java file that will be called for its public String solve() method to answer a problem. The method receives project-defined Java class RP, which contains a collection of RF, which each contain a collection of RO, which each contain several RA which, finally, boil down to String, String pairs (a name and a value). My question is, (how) can I have that solve() method pass its RP object to Clojure where I believe I can do all the work to generate a solution more effectively, and eventually return a String solution back?
EDIT: What I'm looking for is some way of saying, String answer = toClojure(RP); and in Clojure I'll be able to do the equivalent of RP.getRF().getRO().getRA().getName(), where each of these functions is defined in the Java classes.
Just pass it the object reference, same as you would pass it to a java method. Clojure doesn't need any special magic to receive java objects.
I'm converting some python code to java, and have a situation where I need to call methods of an object but don't know which methods until runtime. In python I resolve this by using getattr on my object and passing it a string that is the name of my method. How would you do something similar in Java?
Class.getField is your friend. It probably won't be very straightforward though since Python is dynamically typed and Java is statically typed (unless you know the types of your fields in advance.)
EDIT: How to translate these examples. http://effbot.org/zone/python-getattr.htm
Attribute Lookup
Python
//normal
value = obj.attribute
//runtime
value = getattr(obj, "attribute")
Java
//normal
value = obj.attribute;
//runtime
value = obj.getClass().getField("attribute").get(obj);
Method Call
Python
//normal
result = obj.method(args)
//runtime
func = getattr(obj, "method")
result = func(args)
Java
//normal
result = obj.method(args);
//runtime
Method func = obj.getClass().getMethod("method", Object[].class);
result = func.invoke(obj, args);
In the simpler cases, you need to know whether you have a field or a method. esp as they can have the same name. Additionally methods can be overloaded, so you need to know which method signature you want.
If you don't care which method or field you get, you can implement this as a helper method fairly easily.
You can start here to learn about Java Reflection.
You can use java reflection but there is no exact equivalent of getattr.
In Java you do this with the Reflection API (and it's usually pretty cumbersome).
MethodUtils in Apache Commons BeanUtils project may make it a bit easier to work with, though it's a pretty hefty dependency for something simple like this.
You should use the Reflection API. Since the pure API is a bit ... unapproachable, you should have a look at helpers like commons beanutils or reflections.
The easiest way to handle this is to create a Map object in Java class & keep adding the name value pairs & retrieve it accordingly though it might not support different types that setAttr supports.