What is this type of passing constructor to a method called in Java (the Class_name is an internal class)?
method_name(new Class_name(arguments));
How can we pass constructor without having an instance of the object?
Well, actually new Class_name(arguments)
will create a new instance of the class. A construction might be useful - it is more concise than
Class_name instance = new Class_name(arguments);
method_name(instance);
but you would not be able to access instance
later on.
As has been said, you are passing a new object.
If you want to pass just the information about this class, then your method would need to take a Class an an argument, for example...
public void method_name(Class clz) { ... do something... )
You would call it like this...
method_name( Class_name.class);
The other thing doing literally what you wanted would be to give the Constructor, which you can get, for example, by...
Constructor const = Class_name.class.getConstructor( ArgumentType.class, AnotherArgumentType.class, ...);
for example...
Constructor const = Class_name.class.getConstructor( String.class);
...if your constructor took one String
argument.
And then call your method...
public void method_name(Constructor constructor) { ... do something... )
... with...
method_name( const );
The last way is very specific and I doubt that it's actually what you NEED, no matter what you think you might need.
new creates a object and this is passed to the function. You are not passing class you are passing "new" of that class which will create a object
You are not passing a constructor, an instance :
When you do :
MyClass myClass = new Myclass();
method_name(myClass);
You have an instance of MyClass
into myClass
. then you call method_name
with myClass
as an argument
So this can be shortened as :
method_name(new Myclass());
These types of use cases are very common for Decorator design pattern , where you do not require the intermediate objects.
Example:
FileReader fr = new FileReader(filename);
LineNumberReader lnr = new LineNumberReader(fr);
or
LineNumberReader lnr = new LineNumberReader(new FileReader(filename));
Take a look at I/O classes from nio framework for more understanding on these types of use cases.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.