How to use a method reference inside an Optional.map() - java

I have a Optional.
Optional<AssetEvent> latestEvent = ...
I want to a add a field from inside the Event to a List if Present.
latestEvent.map(event -> event.getTimestamp()).ifPresent(latestList::add);
My IDE (Intelij) shows me "Lambda can be replaced with method reference" on event.getTimestamp()
refactoring to
latestEvent.map(this::getTimestamp).ifPresent(latestList::add);
gives me an Error because this will refer to the surrounding Object in what the code is executed. How can I refer to the method of the Object inside the Optional latestEvent

Use the class name. For example:
latestEvent.map(AssetEvent::getTimestamp).ifPresent(latestList::add);
Assuming AssetEvent is the name of the class having the getTimestamp method.

Related

Accessing a Scala object from Java code

I am trying to use a Scala class that has a default argument:
object SimpleCredStashClient {
def apply(kms: AWSKMSClient, dynamo: AmazonDynamoDBClient, aes: AESEncryption = DefaultAESEncryption)
...
}
When I try to instantiate an instance of this class from Java, I get the error:
Error:(489, 43) java: cannot find symbol
symbol: method SimpleCredStashClient(com.amazonaws.services.kms.AWSKMSClient,com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient)
location: class com.engineersgate.build.util.CredentialsUtil
DefaultAESEncryption is a Scala object. How do I access the Scala object in Java?
Default arguments become synthetic methods of the form <meth>$default$<idx>(). Further, instances of an object A may be found at A$.MODULE$ (if A is a top-level object), or at outer.A() (if A is defined as something like class O { object A }).Therefore, there are two ways to do this:
Direct usage of object:
SimpleCredStashClient.apply(
kms,
dynamo,
DefaultAESEncryption$.MODULE$
);
Default argument:
SimpleCredStashClient.apply(
kms,
dynamo,
SimpleCredStashClient.apply$default$3()
);
The first one certainly looks better, but if the default argument ever changes, you'll have to update this code too. In the second one, the argument is whatever the default argument is, and will only break if the argument stops having a default, or changes its index. Scala uses the second method when compiled.

How to call method of a unknown object

I want to do something different with java reflection. The program i written to add global listeners to java components when applets are opened from browser. An event fired and i get event source object. Here i don't know the actual class name that object referring to.
if(object.getClass.getName().contains("oracle.ewt.laf.basic.BasicTabBarUI$Menu"))
{
// here we can invoke methods,fields,etc using reflection
}
I can call the methods of BasicTabBarUI$Menu class with reflection.
Suppose now i have the following lines with me in the above if block
LWMenuItem menuItem = (LWMenuItem)object;
menuItem.getLabel());
I don't want to specify LWMenuItem class name , instead i want to call its method getLabel(). If we know the class name , we can do as above. But how can we do same with reflection. How can we do casting in reflection?
You don't need to do casting, except of the result of calling the method. Just use the object's Class object, which has a getMethod method that will return a Method object for the method you want, then invoke it:
Class cls = object.getClass();
Method getLabel = cls.getMethod("getLabel", null);
String label = (String)getLabel.invoke(object, null);
You can continue working with the basic object when using the return value from getLabel():
Method getLabelMethod = object.getClass().getMethod("getLabel");
Object menuItem = getLabelMethod.invoke(object);
menuItem.getClass().getMethod("getName").invoke(menuItem); // or whatever...

Java - Multiple Package In Eclipse Issue

I have the following set of packages within my source folder.
The packages are shapes,model,views.
Say I have a class file in my model folder that has the following piece of code:
shapes.interfaceforshapes[][] temp = model.get2dshapearray();
if(temp[x][y].getClass().isInstance(shapes.cTriangle)){
}
Please note in the above code temp[x][y] will return a class that interfaces my shapeInterface
and all classes within the shapes folder interface this.
Am I doing the correct thing to say "Is the class within my array of type cTriangle"?
I currently get the error:
shapes.cTriangle cannot be resolved to a variable
but I don't want to match a variable, I want to test it agaisnt the class cTriangle within my package shape.
Thanks
Use instanceOf operator if you want to check if the object is an instance of a certain class, while the isInstance method expects an instance of a class.
if( temp[x][y] instanceOf shapes.cTriangle) {//dosomething }
That is not how isInstance(Object) works. You have to call it on a class and pass in the object you want to match. You would do:
shapes.cTriangle.class.isInstance(temp[x][y]);
assuming cTriangle is a class and temp[x][y] returns an object and you want to check if that object is of type cTriangle.

Java/Android Get Parent Instance For Invoking Method

I have a method which I am trying to call dynamically. That method has an argument 'stringValue'. The method I am trying to invoke is in the parent (receivers??) class.
I can't figure out how to get the reference back to the parent
java.lang.reflect.Method method;
method = Class.forName("com.blah.MyActivity").getMethod("myFunction", String.class);
method.invoke(this,stringValue);
Gives the error:
'Message expected receiver of type com.blah.MyActivity, but got com.blah.MyActivity$SubTask'
I suspect you want:
method.invoke(MyActivity.this, stringValue);
The MyActivity.this part is the way of getting to the enclosing instance of MyActivity.
See section 15.8.4 of the JLS for more details.

Utilising Javassist to provaide overloading based on return type

Ive used Javassist to dynamically change the return type of a function call, but its not working.
Ive got a call that is defined in the source code as simply:
Boolean getResult(){return true;}
But then at run time I dynamically change it to:
String getResult(){return "true"}
I then call it as:
Object o = myobject.getResult();
And get a MethodNotFound exception. If I use reflection I can see my new method on the object, but the call is failing, apparently because its somehow bound to the old return type.
If I call the new method reflectively (slight pseudocode..):
Method m = myobject.getClass.GetDeclaredMethods().(...find method named GetResult...)
Object o = m.invoke(myObject);
Then all works fine, and I can switch between manipulated and non manipulated byte code without issue, and I can see that the type of O is either String or Boolean accordingly.
Any ideas why?

Categories

Resources