"Good" method to call method on each object using Stream API - java

Is it possible to run a method, in a consumer, like a method reference, but on the object passed to the consumer:
Arrays.stream(log.getHandlers()).forEach(h -> h.close());
would be a thing like:
Arrays.stream(log.getHandlers()).forEach(this::close);
but that's not working...
Is there a possibility with method references, or is x -> x.method() the only way working here?

You don't need this. YourClassName::close will call the close method on the object passed to the consumer :
Arrays.stream(log.getHandlers()).forEach(YourClassName::close);
There are four kinds of method references (Source):
Kind Example
---- -------
Reference to a static method ContainingClass::staticMethodName
Reference to an instance method of a particular object containingObject::instanceMethodName
Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName
Reference to a constructor ClassName::new
In your case, you need the third kind.

I suppose it should be:
Arrays.stream(log.getHandlers()).forEach(Handler::close);
Provided the log.getHandlers() returns an array of objects of type Handler.

Sure, but you must use the correct syntax of method reference, i.e. pass the class to which the close() method belong:
Arrays.stream(log.getHandlers()).forEach(Handler::close);

Related

Safeguarding method parameters in java

I want to safe guard my method parameters that were passed to the called method from being changed accidentally. I know that we can use final keyword to achieve this (partially) like the following in the method signature.
public void someMethod(final int intVal, final MyClass myobj){}
With the help of the above signature I cannot change the value of intVal, but however I can change the values (members) of myobj (I can safe guard only the reference not being changed, but not the members of the referencing object, that why I said partial).
Now I am looking to safe guard my myobj members either, getting changed in the called method someMethod.
In my knowledge I could achieve this using the following ways
Create an immutable class and pass it as a parameter
Deep copy the object and send the cloned object to the method.
Is there any better apporach to safeguard the method parameters?

Difference between "passing reference after assigning an object" and "passing object using new keyword" to a method in java?

What difference does it makes?
Let's think we have a method in java as following:
void demoMethod(MyClass mc){
// some operations
}
First type:
demoMethod(new MyClass()); // directly passing an object
Second type:
MyClass mc = new MyClass();
demoMethod(mc); // passing reference of an object
No difference in terms of the method's behavior on that reference. The first code can semantically translate to the second one. Eventually, the object created using new MyClass() needs to be stored somewhere so that it can be re-loaded and passed to the method.
However, using the second code you can re-use the reference.
It doesn't make any difference for demoMethod. Actually in both cases you are passing reference only.
However if you want to use the information after demoMethod does some operation in the calling method, you can't do that in first type.
Assume your demoMethod sets a property of your MyClass object to true or false, you don't have any way to find out what it's value is set to.
So, you can do something like
demoMethod(mc);
if(mc.isMyProperty()==true)
System.out.println("mc is changed");

How does the special variable "this" know exactly which Object to refer to in a program in JAVA? [duplicate]

This question already has answers here:
Using the keyword "this" in java [duplicate]
(12 answers)
Closed 9 years ago.
If the special variable this refers to an Object in a variable/method that is being used. How does it know exactly which object it must refer to out of various objects in a program?
The mechanism is almost disappointingly simple.
Each instance method actually takes one more argument than you declare for it, and that extra argument is assigned to this. Java syntax just thinly disguises this. When you write
list.get(0);
you have actually written
get(list, 0);
in a slightly modified way. The Java runtime resolves which get method to call by inspecting the type of that first argument and locating the appropriate get method in its class.
this points to the current object instance that it is used in.
If you define a class A with a method() that contains a this reference then you create two instances of the class
A a1 = new A();
A a2 = new A();
If you call a1.method() then this will refer to a1, if you call a2.method() then this will refer to a2
A a = new A();
a.doSomething(i) // is same as calling doSomething(a, i).
So, internally this refers to "a". The first argument to the function will be the object (there will only be one method that will be used by all objects). So, argument o will be the current object which has called this function.
From JAVA LANGUAGE SPECIFICATION
The keyword this may be used only in the body of an instance method,
instance initializer, or constructor, or in the initializer of an
instance variable of a class. If it appears anywhere else, a
compile-time error occurs.
When used as a primary expression, the keyword this denotes a value
that is a reference to the object for which the instance method was
invoked (§15.12), or to the object being constructed.
The type of this is the class C within which the keyword this occurs.
At run time, the class of the actual object referred to may be the
class C or any subclass of C.
The keyword this is also used in a special explicit constructor
invocation statement, which can appear at the beginning of a
constructor body (§8.8.7).
You can also refer to Oracle Tutorials
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
Oracle Java Tutorials
this is a very important keyword that can differentiate between parent and child class objects. this refers to the present context in which object has too be referred to..!!

Java Reflection ArrayList.class.getMethod("get") returns NoSuchMethodException

Why can't I get the "get" method of an ArrayList and invoke it?
I am using reflection to modify within my nested classes. One of my classes has a list of classes so I wanted to be able to use the same logic to get and invoke the get method.
simplified, the line that fails is
ArrayList.class.getClass().getMethod("get")
and it fails, giving me a NoSuchMethodException.
I understand that I could use aList.get() but that's not the point, I need to use reflection since this is in a deeply nested class.
TL;DR
How can I get the "get" method of an array list?
Note that Class#getMethod() has two parameters: a String and an vararg of Class objects. The former is
the list of parameters
that the method declares.
You need to use
ArrayList.class.getMethod("get", int.class);
since the ArrayList#get(int) method has an int parameter.
I initially missed the whole
ArrayList.class.getClass().getMethod("get")
^ ^
| |----------------------------- gets Class<Class>
|----------------------------------- gets Class<ArrayList>
The .class already gets the Class instance for ArrayList. Calling getClass on that will return the Class instance for class Class. You don't want that.
Method methods = ArrayList.class.getMethod("get", int.class);
You do not need to call getClass() method again after .class because when you write .class after a class name, it references the Class object that represents the given class.

reference a method from a class by using a variable

I know how in Java, a class is referenced like com.google.googlemaps.exampleClass.exampleMethod().
Is it possible to interchange the first parts of the referenece (in this case, the com.google.googlemaps) using a variable (Class c)?
EDIT
Ok, after some confusion, I'm going to (try to) provide an example
We have Class A. I can add a new instance of it. Each instance has the variables name (a String), and redir (currently in turmoil). redir is the variable which is supposed to hold the reference for the class, so I can call a specific method from those classes, so redir is like com.google.googlemaps etc.
Like c.exampleMethod()?
Yes, like so
import com.google.googlemaps.ExampleClass;
...
ExampleClass c = new ExampleClass();
c.exampleMethod();
from your example:
com.google.googlemaps.exampleClass.exampleMethod()
the exampleMethod() is a static method.
If you have an object/reference with Type Class<com.google.googlemaps.exampleClass> (Class c) you can call getMethod to get the Method object. And then you could call invoke method to invoke the method.

Categories