can i convert any lambda expression into method reference - java-8

I wonder if can i convert any lambda expression into method reference
for example:
if there is a lambda that execute method with 2 parameters (one of them is from outside)
.map( t -> removeFilesIfNessasary( externalObj, t ) )
can this also converted into method reference?
thanks

Well you could create a class, sort of like this:
class Remover {
private final Object externalObj;
public Remover(Object externalObj){
this.externalObj = externalObj;
}
public removeIf(int t){
removeFilesIfNessasary( externalObj, t);
}
}
and then declare this and use it:
Remover remover = new Remover(externalObj);
.map(remover::remove);
But seriously, this looks really weird; there has to be a compelling reason for you to do this (I can't think of one).

Related

Null Pointer Error when Mocking JDBC Template execute method [duplicate]

I've been trying to get to mock a method with vararg parameters using Mockito:
interface A {
B b(int x, int y, C... c);
}
A a = mock(A.class);
B b = mock(B.class);
when(a.b(anyInt(), anyInt(), any(C[].class))).thenReturn(b);
assertEquals(b, a.b(1, 2));
This doesn't work, however if I do this instead:
when(a.b(anyInt(), anyInt())).thenReturn(b);
assertEquals(b, a.b(1, 2));
This works, despite that I have completely omitted the varargs argument when stubbing the method.
Any clues?
Mockito 1.8.1 introduced anyVararg() matcher:
when(a.b(anyInt(), anyInt(), Matchers.<String>anyVararg())).thenReturn(b);
Also see history for this: https://code.google.com/archive/p/mockito/issues/62
Edit new syntax after deprecation:
when(a.b(anyInt(), anyInt(), ArgumentMatchers.<String>any())).thenReturn(b);
A somewhat undocumented feature: If you want to develop a custom Matcher that matches vararg arguments you need to have it implement org.mockito.internal.matchers.VarargMatcher for it to work correctly. It's an empty marker interface, without which Mockito will not correctly compare arguments when invoking a method with varargs using your Matcher.
For example:
class MyVarargMatcher extends ArgumentMatcher<C[]> implements VarargMatcher {
#Override public boolean matches(Object varargArgument) {
return /* does it match? */ true;
}
}
when(a.b(anyInt(), anyInt(), argThat(new MyVarargMatcher()))).thenReturn(b);
Building on Eli Levine's answer here is a more generic solution:
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.mockito.ArgumentMatcher;
import org.mockito.internal.matchers.VarargMatcher;
import static org.mockito.Matchers.argThat;
public class VarArgMatcher<T> extends ArgumentMatcher<T[]> implements VarargMatcher {
public static <T> T[] varArgThat(Matcher<T[]> hamcrestMatcher) {
argThat(new VarArgMatcher(hamcrestMatcher));
return null;
}
private final Matcher<T[]> hamcrestMatcher;
private VarArgMatcher(Matcher<T[]> hamcrestMatcher) {
this.hamcrestMatcher = hamcrestMatcher;
}
#Override
public boolean matches(Object o) {
return hamcrestMatcher.matches(o);
}
#Override
public void describeTo(Description description) {
description.appendText("has varargs: ").appendDescriptionOf(hamcrestMatcher);
}
}
Then you can use it with hamcrest's array matchers thus:
verify(a).b(VarArgMatcher.varArgThat(
org.hamcrest.collection.IsArrayContaining.hasItemInArray("Test")));
(Obviously static imports will render this more readable.)
I have been using the code in Peter Westmacott's answer however with Mockito 2.2.15 you can now do the following:
verify(a).method(100L, arg1, arg2, arg3)
where arg1, arg2, arg3 are varargs.
I had to use the any(Class type) method to match an array arg being passed as a varargs parameter.
ArgumentMatchers.any(Class type)
Code in the implementation is vararg aware.
reportMatcher(new InstanceOf.VarArgAware(
In my case where matching a String[] arg to a String... param the following worked:-
any(String.class)
Building on topchef's answer,
For 2.0.31-beta I had to use Mockito.anyVararg instead of Matchers.anyVararrg:
when(a.b(anyInt(), anyInt(), Mockito.<String>anyVararg())).thenReturn(b);
Adapting the answer from #topchef,
Mockito.when(a.b(Mockito.anyInt(), Mockito.anyInt(), Mockito.any())).thenReturn(b);
Per the java docs for Mockito 2.23.4, Mockito.any() "Matches anything, including nulls and varargs."
You can accomplish this by passing an ArgumentCaptor capture and then retrieving the varargs as a list using "getAllValues", see: https://stackoverflow.com/a/55621731/11342928
As the other answers make sense and make tests work obviously, I still recommend to test as if the method didn't take a vararg, but rather regular well-defined parameters instead. This helps in situations where overridden methods in connection with possible ambiguous parameters are in place, like an SLF4J-logger:
to test:
jobLogger.info("{} finished: {} tasks processed with {} failures, took {}", jobName, count, errors, duration);
This has a bunch of overrides and the important method being declared like so
Logger.info(String, Object...)
verification:
verify(loggerMock).info(anyString(), anyString(), anyInt(), anyInt(), anyString());
proof that the above works as errors is an integer and not a long, so the following wouldn't run:
verify(loggerMock).info(anyString(), anyString(), anyInt(), anyLong(), anyString());
So you can easily use when() instead of the verify()-stuff to set up the required return value.
And it probably shows more of the intent and is more readable. Captures can also be used here and they are much easier accessible this way.
Tested with Mockito 2.15
In my case the signature of the method that I want to capture its argument is:
public byte[] write(byte ... data) throws IOException;
In this case you should cast to byte array explicitly:
when(spi.write((byte[])anyVararg())).thenReturn(someValue);
I'm using mockito version 1.10.19
You can also loop over the arguments:
Object[] args = invocation.getArguments();
for( int argNo = 0; argNo < args.length; ++argNo) {
// ... do something with args[argNo]
}
for example check their types and cast them appropriately, add to a list or whatever.

Clojure - How to Declare a Collection or Vector of a Record

How Can I define a Record Collection or a Vector of Records?
I have this snippet code:
(defrecord Transaction [a, b, c])
I want define a Transaction collection called LastTransactions to implement a function like this:
(defn can-authorize
"Validate Authorization by Transaction"
[^Transaction transaction, ^LastTransactions lastTransactions]
(... business logic)
)
First Question, is that the right way to do that?
Second, How can i declare that structure?
Clojure's type hints don't offer any type validation - you can use Clojure Spec or Plumatic Schema for that. They only serve for the compiler to prevent reflection when Java methods are called on the parameters. For that purpose, you don't need to type hint a vector since Clojure's core functions for collections (first, conj, etc.) by design don't require reflection on standard collections.
However, if you need, you can type-hint the elements that you extract from the lastTransaction sequence, for example:
(defn can-authorize
"Validate Authorization by Transaction"
[^Transaction transaction, lastTransactions]
...
(for [^Transaction t lastTransactions]
(...do-something-with t))
Type-hints are used to avoid reflection. They are not used to statically type function or constructor args.
Just use basic ^java.util.List type-hint instead of ^LastTransactions. In this case, any use of wrong lastTransactions in the body of the function will fail with ClassCastException. However, it won't check the type of elements in that list. To do so, use type hinting everytime you work with elements of lastTransactions.
Example 1 with type hinting:
(defn can-authorize
[^Transaction transaction, ^java.util.List lastTransactions]
(.size lastTransactions)
)
In this case, decompiled java code will look like:
// Decompiling class: user$can_authorize
import clojure.lang.*;
import java.util.*;
public final class user$can_authorize extends AFunction
{
public static Object invokeStatic(final Object transaction, Object lastTransactions) {
final Object o = lastTransactions;
lastTransactions = null;
return ((List)o).size();
}
public Object invoke(final Object transaction, final Object lastTransactions) {
return invokeStatic(transaction, lastTransactions);
}
}
Example 2 without type hinting:
(defn can-authorize [^String transaction, lastTransactions]
(.size lastTransactions))
decompiled to:
// Decompiling class: user$can_authorize
import clojure.lang.*;
public final class user$can_authorize extends AFunction
{
public static Object invokeStatic(final Object transaction, Object lastTransactions) {
final Object target = lastTransactions;
lastTransactions = null;
return Reflector.invokeNoArgInstanceMember(target, "size", false);
}
public Object invoke(final Object transaction, final Object lastTransactions) {
return invokeStatic(transaction, lastTransactions);
}
}
Compare the resulted return statements:
with type hinting
return ((List)o).size();
without type hinting
return Reflector.invokeNoArgInstanceMember(target, "size", false);
PS: code decompiled by using clj-java-decompiler

Combining functions and consumers with double-column notation

I often use the double-colon notation for brevity.
I am writing the following method that takes a short list of entities, validates them, and saves back to database.
#Override#Transactional
public void bulkValidate(Collection<Entity> transactions)
{
Consumer<Entity> validator = entityValidator::validate;
validator = validator.andThen(getDao()::update);
if (transactions != null)
transactions.forEach(validator);
}
I'd like to know if there is a shorthand syntax avoiding to instantiate the validator variable
Following syntax is invalid ("The target type of this expression must be a functional interface")
transactions.forEach((entityValidator::validate).andThen(getDao()::update));
You could do that, but you would need to cast explicitly...
transactions.forEach(((Consumer<Entity>)(entityValidator::validate))
.andThen(getDao()::update));
The thing is that a method reference like this entityValidator::validate does not have a type, it's a poly expression and it depends on the context.
You could also define a method to combine these Consumers:
#SafeVarargs
private static <T> Consumer<T> combine(Consumer<T>... consumers) {
return Arrays.stream(consumers).reduce(s -> {}, Consumer::andThen);
}
And use it:
transactions.forEach(combine(entityValidator::validate, getDao()::update))

How to detect if JavaScript (ES6) class has a non-default constructor?

I would like to know by some form of reflection or other means if a given ES6 class has a user-written non-default constructor, or not.
Assuming that user-provided constructor has one argument or more, you can do that by checking the length property of the function(class). But if the constructor takes no argument, there is simply no way as far as I know
function Person(fName, lName) {
this.firstName = fName;
this.lastName = lName
}
console.log(Person.length);
function Person2() {}
console.log(Person2.length);
class Person3 {
constructor(f,l) {}
}
console.log(Person3.length);
class Person4 {
}
console.log(Person4.length);
You can invoke the Classname.prototype.constructor.toString() (where Classname is the inspected class name) and get the source string for the class. Which you can then parse and see if it was a constructor declared or not.
Presumably, you need a decent parser for that, but it's another story.
References:
http://www.ecma-international.org/ecma-262/6.0/#sec-function.prototype.tostring

Dropwizard deserializing generic list from JerseyClient

I wanted to implement a generic class to use for caching results from a REST API in a local MongoDB-instance. For this to work, I need to deserialize a collection I get from JerseyClient:
Response response = this.source.request().get();
List<T> list = response.readEntity( new GenericType<List<T>>() {} );
// ... do stuff with the list
Let's say I'm using this piece of code in a context of T relating to a class Foo. The really weird thing is, after the readEntity call, list is not a List<Foo>, instead is a List<LinkedHashMap>. How is that even possible, when I've clearly declared the Generic T to be Foo?
What do I have to do to get a proper List<T>, i.e. List<Foo> instead?
Note: If I remove the generic, and use
List<Foo> list = response.readEntity( new GenericType<List<Foo>>() {} );
directly instead, it works fine, but I really need that generic to be there!
Java's most popular excuse for Generics: Type Erasure
If you can pass your class type as Class<T> clazz, then you can use this:
GenericType<List<T>> genericType = new GenericType<>(new ParameterizedType() {
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
public Type getRawType() {
return List.class;
}
public Type getOwnerType() {
return null;
}
});
response.readEntity(genericType);
You can use
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;
import javax.ws.rs.core.GenericType;
GenericType<List<T>> genericType = new GenericType<>(
ParameterizedTypeImpl.make( List.class, new Type[]{classType}, null));

Resources