java 7: Get optional nested POJO property - java

I'm coming from a Swift background jumping back to Android and i'm used to using notation of this
let fooOptional = foo?.fooer?.fooest
print(fooOptional)
In java 8, this is possible:
Optional.of(new Foo())
.map(Foo::Fooer)
.map(Fooer::Fooest)
.ifPresent(System.out::println);
However, in java 7, there is no real out of the box way of doing this without resorting to later versions of Android, which does not work with our minimum SDK specs. Is there one?

If the pojos set up have getter calls to grab nested properties, you can use reflection to grab the optional get calls and walk down the nest:
public class NestedOptional<T> {
public static <T> Optional<T> fromNullable(Object obj, String... calls) {
if (obj == null) {
return Optional.absent();
}
for (String call: calls) {
try {
obj = obj.getClass().getMethod(call).invoke(obj);
if (obj == null) {
return Optional.absent();
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Couldn't call " + call + "() on " + obj, e);
}
}
return Optional.of(obj);
}
}
If there is a null pointer, it will return Guava's optional object thats available pre java 8.
With this, you can then:
Optional<Fooest> fooOptional = NestedOptional.fromNullable(foo, "getFooer", "getFooest");
if (fooOptional.isPresent()) {
System.out.println(fooOptional.get().toString());
}

Related

Avoiding code duplication when checking for default responses

I have a Java program that calls an external API (RealApi in the code below) and sometimes I want to avoid calling this API and instead return pre-constructed responses (generated by FakeApi).
So, I ended up duplicating this kind of construct in most of my methods:
public Type1 m1(String s) {
try {
Type1 r = FakeApi.m1(s);
if (r != null) {
return r;
}
} catch (Exception e) {
// log error
}
return RealApi.m1(s);
}
What are some options to avoid duplicating this try/catch block everywhere? It's important that if FakeApi throws an exception or returns null, the RealApi must be called.
One option would be encapsulate the error checking behaviour into its own method:
public <T> T fakeOrReal(Supplier<T> fake, Supplier<T> real) {
try {
T r = fake.get();
if (r != null) {
return r;
}
}
catch (Exception e) {
// log error
}
return real.get();
}
You can then just call it with
public Type1 m1(String s) {
return fakeOrReal(() -> FakeApi.m1(s), () -> RealApi.m1(s));
}
This is not as simple as Thomas Preißler's answer but it will help you not repeat any method at all. So if you expand the interface, you have to modify only the concrete classes and not the linker which describes the actual behavior you want.
Create an interface that contains all the methods of RealApi:
interface Api {
Type1 m1(String s);
}
Then a class that does the actual call:
class ConcreteApi implements Api {
public Type1 m1(String s) {
return RealApi.m1(s);
}
}
Then create your FakeApi:
class TotallyFakeApi implements Api {
public Type1 m1(String s) {
return FakeApi.m1(s);
}
}
Now, the tricky part to avoid repeating yourself:
private static Object callImplementation(Api api, Method method, Object[] methodArgs) throws Exception {
Method actualMethod = api.getClass().getMethod(actualMethod.getName(), actualMethod.getParameterTypes());
return actualMethod.invoke(api, methodArgs);
}
Api fakeOrReal(Api fakeApi, Api realApi) {
return (Api) Proxy.newProxyInstance(
FakeApi.class.getClassLoader(),
new Class[]{Api.class},
(proxy, method, methodArgs) -> {
try {
Object r = callImplementation(fakeApi, method, methodArgs);
if (r != null) {
return r;
}
} catch (Exception e) {
// logError(e);
}
return callImplementation(realApi, method, methodArgs);
}
);
}
Get the actual implementation like this:
Api apiToUse = fakeOrReal(new TotallyFakeApi(), new ConcreteApi());

How to avoid NoSuchMethodException with primitives in Java

I'm working on legacy project and I've trapped into situation when I have to make additional init stuff with action object. In this code AdmAction is a basic interface and inside method I could have any of it's implementation. Some of implementations require additional properties must be initialized with values from utilParams.
private void initActionParams(AdmAction action, Map<String, Object> utilParams) {
if (utilParams == null) {
return;
}
utilParams.forEach((paramName, value) -> {
try {
Method setterMethod = action.getClass().getMethod(setterFor(paramName), value.getClass());
setterMethod.invoke(action, value);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
log.error(e.getMessage(), e);
throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
}
});
}
utilParams looks like "serviceId": 10 of "ticketId": "8a30f5a7-809c-4551-8833-c2a60e4c6fd9".
Code works fine when value is an Object type (String, Integer etc.) and when setter method of AdmAction implementation consumes the same.
But there's one problem when I've got for example Integer type in utilParams and setter method in action which consumes int.
Of course code throws NoSuchMethodException
Example:
Action impl:
public class Foo implements AdmAction {
// ...
public void setServiceId(int serviceId) {
this.serviceId = serviceId;
}
}
Causes an exception.
I've tried to improve code with method search:
private void initActionParams(AdmAction action, Map<String, Object> utilParams) {
if (utilParams == null) {
return;
}
utilParams.forEach((paramName, value) -> {
try {
Method setterMethod = Arrays.stream(action.getClass().getDeclaredMethods())
.filter((Method method) -> method.getName().equals(setterFor(paramName)))
.findFirst()
.orElseThrow(NoSuchMethodException::new);
setterMethod.invoke(action, value);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
log.error(e.getMessage(), e);
throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
}
});
I guess it's a little bit brute for actual case.
Can anybody help me find the way to write better and more aesthetic code?
You could use java.beans.Statement for this, which will do unboxing.
java.beans.Statement(action, setterFor(paramName), new Object[] {value})
.execute();

How I can transfer atrributes values from a Objects to another

I want tranfers attributes values from a object that came from my Entity manager to a new object.
The return Object is always null
public class ReflectionUtil {
public static Object copyAttributesFromTo(Object a, Object b) throws IllegalArgumentException, IllegalAccessException {
Field[] fieldsFromFirstClass = a.getClass().getDeclaredFields();
Field[] fieldsFromSecondClass = b.getClass().getDeclaredFields();
for (Field currentFieldFromTheFirstClass : fieldsFromFirstClass) {
for (Field currentFieldFromTheSecondClass : fieldsFromSecondClass) {
String nameOfTheFirstField = currentFieldFromTheFirstClass.getName();
String nameOfTheSecondField = currentFieldFromTheSecondClass.getName();
if (!Modifier.isFinal(currentFieldFromTheFirstClass.getModifiers())) {//Dispensa os Final
if (!currentFieldFromTheFirstClass.isAnnotationPresent(Id.class)) {//Não sobescreve campo id
if (nameOfTheFirstField.equals(nameOfTheSecondField)) {
currentFieldFromTheFirstClass.setAccessible(true);
currentFieldFromTheSecondClass.setAccessible(true);
currentFieldFromTheSecondClass.get(b));
currentFieldFromTheFirstClass.set(a, currentFieldFromTheSecondClass.get(b));
}
}
}
}
}
return a;
}
}
In the Facade call I always have to put all the attribute values to new object
public void update(Profile object) {
dao.beginTransaction();
Profile persistedObject = dao.find(object.getId());
persistedObject.setName(object.getName());
dao.commitAndCloseTransaction();
}
So I think to create some like that
public void update(Profile object) {
dao.beginTransaction();
Profile persistedObject = dao.find(object.getId());
ReflectionUtil.copyAttributesFromTo(persistedObject , object);
dao.commitAndCloseTransaction();
}
really miss understood why u are using 2 loop? .. if the classes are same . u dont need to do it .. just do it in 1 loop .. and use fields get for obj which is holding data .. and use set for to set .. here is the more better way .. if the same object is required u can use generics .. and same object type will be required ( request return type )
public static <T> T copyAttributesFromTo(T value, T dataHolder) throws IllegalArgumentException, IllegalAccessException {
if (value == null || dataHolder == null) {
throw new IllegalArgumentException();
}
final Field[] fields = value.getClass().getDeclaredFields();
for (Field field : fields) {
if (!Modifier.isFinal(field.getModifiers())) {
field.setAccessible(true);
field.set(value, field.get(dataHolder));
}
}
return value;
}
The return Object is always null
It is impossible for the return object (i.e. whatever a contains when you return) to be null.
It is easy to see that the code does not change the reference a. There are no assignments to it in the method, so it cannot change.
The other possibility was that you called the method with a null value for a. But if you did that, the first line of the method calls a.getClass() and that will throw an NPE if a is null.
TL;DR - it is impossible.
So what does this mean?
Here are the most likely explanations:
You are mistaken that null is being returned. Perhaps the method is not being called? Perhaps, it is not returning?
Maybe you have misinterpreted the evidence in some other way. It is hard to know without seeing the code ... and the evidence.
Maybe you don't mean that the method is returning Object; i.e. I misunderstood the question. (Your problem description is pretty unambiguous though ...)
I make a change in the code and works to update for me
public static Object copyAttributesFromTo(Object a, Object b) throws IllegalArgumentException, IllegalAccessException {
Field[] fieldsFromFirstClass = a.getClass().getDeclaredFields();
Field[] fieldsFromSecondClass = b.getClass().getDeclaredFields();
//JSFMessageUtil.addMsgLog(JSFMessageUtil.matricula, ReflectionUtil.class.getCanonicalName(), "ReflectionUtil: Aqui");
for (Field currentFieldFromTheFirstClass : fieldsFromFirstClass) {
for (Field currentFieldFromTheSecondClass : fieldsFromSecondClass) {
Object nameOfTheFirstField = currentFieldFromTheFirstClass.getName();
Object nameOfTheSecondField = currentFieldFromTheSecondClass.getName();
if (!Modifier.isFinal(currentFieldFromTheFirstClass.getModifiers())) {//Dispensa os Final
//if (!currentFieldFromTheFirstClass.isAnnotationPresent(Id.class)) {//Não sobescreve campo id
if (nameOfTheFirstField.equals(nameOfTheSecondField)) {
currentFieldFromTheFirstClass.setAccessible(true);
currentFieldFromTheSecondClass.setAccessible(true);
//JSFMessageUtil.addMsgLog(JSFMessageUtil.matricula, ReflectionUtil.class.getCanonicalName(), "ReflectionUtil: " + currentFieldFromTheSecondClass.get(b));
currentFieldFromTheFirstClass.set(a, currentFieldFromTheSecondClass.get(b));
}
//}
}
}
}
return a;
}
The call
public void update(Aluno a) {
try {
Aluno aluno = new Aluno();//(Aluno) em.find(Aluno.class, a.getId());
em.getTransaction().begin();
//aluno.setNome(a.getNome());
ReflectionUtil.copyAttributesFromTo(aluno, a);
em.merge(aluno);
em.getTransaction().commit();
} catch (Exception e) {
System.out.println("Error " + e.getLocalizedMessage());
JOptionPane.showMessageDialog(null, e.getLocalizedMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
} finally {
em.close();
}
}

Dynamic null check [duplicate]

This question already has answers here:
Check chains of "get" calls for null
(11 answers)
Closed 3 years ago.
I intend to make a common dynamic null check function on any object before doing some work on it.
For example:
Class A{
B b;
// with getters and setters of b
}
class B{
C c;
//with getters and setters of c
}
class C{
BigInteger d;
//with getters and setters of d
}
now, I want to check whether objA.getB().getC().getD() returns some value or throws NullPointerException?
By common I mean I can pass any kind of object to it, something like below function
CheckNull.checkingDynamicNull( "objA.getB().getC().getD()" )
will return me true or false depending on the case.
Any ideas?
Unfortunately it is not possible to pass a funktion into a method in Java (yet, Java 8 will). Also, if you pass the variable name as String this wont work, since the recieving method has no way of knowing what Object is mapped to that variable (if you ignore reflection but even with that you are screwed if its a local variable).
Another way would be to do something like this
boolean nullCheck(Object obj, String Methods)
and then parse the String to Methods and invoke them on the object. But that wont work if you have Methods with arguments.
In short: It's more trouble then it's worth
In the most cases you want to have something like this
if(object == null){
//error behavior
}
This assumes that you want to throw a certain Exception, have means to get a value for the null object elswhere or want to do something before you throw an exception.
If you simply want to throw an Exception (that is not a NullPointerException)
assert object != null
What about this:
public boolean checkingDynamicNull(A objA) {
try {
objA.getB().getC().getD().toString();
} catch(NullPointerException npe) {
return true;
}
return false;
}
To know if a statement would return null, you would have to execute it first. Even if you somehow manage to execute the statement given in String to your method, it would be no different than just running it and checking whether the result is null, or catching the NullPointerException.
You are looking for something that will be part of Java 8 (or 9 or 10?) soon. Cf. http://viralpatel.net/blogs/null-safe-type-java-7-nullpointerexception/
With reflection it could be something like that:
nullCheck(objA, "getB", "getC", "getD" );
public static boolean nullCheck(Object obj, String... methods) {
Object o = obj;
Class<?> clazz = obj.getClass();
Method method = null;
try {
for( String name : methods ) {
method = clazz.getMethod( name, null );
o = method.invoke( o, null );
clazz = method.getReturnType();
}
} catch( NullPointerException e ) {
System.err.println(clazz.getSimpleName()+"(null)."+method.getName());
return false;
} catch( NoSuchMethodException e ) {
e.printStackTrace();
} catch( SecurityException e ) {
e.printStackTrace();
} catch( IllegalAccessException e ) {
e.printStackTrace();
} catch( IllegalArgumentException e ) {
e.printStackTrace();
} catch( InvocationTargetException e ) {
e.printStackTrace();
}
return true;
}
System.out.println(nullCheck(GraphicsEnvironment.getLocalGraphicsEnvironment(), "getDefaultScreenDevice", "getDisplayMode", "toString"));
System.out.println(nullCheck(GraphicsEnvironment.getLocalGraphicsEnvironment(), "getDefaultScreenDevice", "getFullScreenWindow", "doLayout"));
brings
true
false
'Window(null).doLayout'
you can achieve this by using reflection, here is your method:
public boolean dynamicNullCheck(Object o, String path) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Object object= o;
for (String element : path.split("\\."))
{
Field field = object.getClass().getDeclaredField(element);
field.setAccessible(true);
Object fieldVal = field.get(object);
if (fieldVal!=null)
{
field.setAccessible(true);
object = fieldVal;
}
else
{
return true;
}
}
return false;
}
use it by giving your root element and path to each object, ie dynamicNullCheck(objA,"b.c.d")

Java global isEmpty() method

I have an application which uses code that produces various types of objects and data structures, returning them as Object instances, and would like a generic way of establishing whether any of those objects is "empty" (or null).
(This is not a matter of design, or of whether such a method should be used, but a question of optimizing the solution to an existing requirement.)
So, here is a simple go:
public static boolean isEmpty(Object content)
{
if (content == null)
{
return true;
}
else if (content instanceof CharSequence)
{
return (((CharSequence)content).length() == 0);
}
else if (content instanceof Collection<?>)
{
return ((Collection<?>)content).isEmpty();
}
else if (content instanceof Object[])
{
return (((Object[])content).length == 0);
}
else // Use reflection (an exaggeration, for demo purposes)
{
try
{
Method isEmpty = content.getClass().
getDeclaredMethod("isEmpty", (Class<?>[])null);
if (isEmpty != null)
{
Object result = isEmpty.invoke(content, (Object[])null);
if (result instanceof Boolean)
{
return (Boolean)result;
}
}
}
catch (Exception e)
{
}
}
return false;
}
Any ideas for potential improvements, in terms of either performance, or coverage?
For instance, reflection could be also used to establish whether the object has a length() or size() method, invoke it and see if the result is 0. (In reality, reflection is probably too much, but I am including it here for completeness.)
Is there a top-level class very commonly used, which has a length() or size() method, instead of the isEmpty() method, to include in the above case, similarly to Collection that has isEmpty()?
Instead of the ugly instanceofs, split up the method into several methods with the same name but different args. e.g.
static boolean isEmpty(Object[] array)
static boolean isEmpty(Collection collection)
static boolean isEmpty(CharSequence cs)
Instead of reflection, if you really want your own interface for special objects, declare that interface, and then, for consistency with the above, offer the static utility
static boolean isEmpty(IMayBeEmpty imbe);
This method would at least solve your problem of the generic isEmpty(Object) problem. However, you don't get compile time safety with this, and calling it without the method existing for the exact type requested will yield a runtime error. Note the "MethodUtils" class is from apache commons-beanutils, though you could easily use reflection directly, but for the sake of simplicity, i'm using beanutils here.
The "invokeExactcMethod" method looks for a static method in the given class with the given name that has the compatible parameters of the object array being passed. So if the runtime type of the object is ArrayList, it would look for isEmpty(ArrayList) then isEmpty(AbstractList) then isEmpty(List). It then invokes that method if it can find it, otherwise it throws a NoSuchMethodException.
public class MyUtility {
static boolean isEmpty(Object object) {
if (object == null) {
return true;
}
else {
try {
return MethodUtils.invokeStaticMethod(
MyUtility.class, "isEmpty", new Object[]{object});
}
catch (NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
}
the "invokeExactStaticMethod" is more deterministic and doesn't use assignment compatibility, but exact signature matching. That means isEmpty(List) would never match anything because you can't construct anything of that type.

Categories