Creating an object without a default constructor - java

I have a package which has some N number of classes and I'm scanning all the classes and initializing them through a method. All the classes with a default constructor are being initialized but the ones without default(zero argument) constructor throws an exception. Does anyone know how to create an object without default constructor?
P.S. I need a java code.

Use Class#getConstructors() to find a defined constructor, and call that instead.

You can try looking here. It explains how to create objects using Java reflection.
Or just Google: java constructor reflection. I got this one using the "I'm feeling lucky" feature

Related

Calling an abstract method from an interface without overriding it

I am working on a Java project and want to understand the source code before implementing mine into it. The problem im facing is, how can the source code uses the abstract method from an interface without actually overriding it?
At first, I came to this statement:
DeviceService deviceService = context.deviceService();
It is using 'context' to call the method deviceService(). Then, I went up to see where was 'context' being initialized. Then I found this:
private final LinkDiscoveryContext context;
So, 'context' is a type of LinkDiscoveryContext. But then, 'LinkDiscoveryContext' is actually an interface. and the deviceService() is actually an abstract method without having any concrete definition of how the method should do.
I thought we cannot call the method of an interface unless we override it, but why is it working? I may be lack in developer knowledge in Java, and might have provided not enough information. But if the community has any guessing that could result in this working, please share with me.
Thanks in advance.
The class you mention has the constructor that takes instance of LinkDiscoveryContext as argument. So basically you assign a specific implementation to that field using class constructor.
Look for constructor usages to check where it is called from. Hence you will know from which place(s) does that implementation come.

No arg constructor and De serialization in Java

DeSerialization using the Serializable interface mechanism uses Reflection to deserialize the Object bytes to Object. But default no arg constructor is not called during this process and hence its not needed. But all the frameworks like Spring,Hibernate etc need no arg constructor even though they use Reflection. Isn't this contradictory or am I missing something?
The builtin standard deserialization does not use standard reflection to create instances.
Standard reflection can not create instances without calling a constructor (not necessarily the no arg constructor). So any framework only using standard reflection will need to call a constructor for instance creation.
To create instances without calling a constructor you need some kind of jvm-vendor specific extension, like Unsafe. It is up to the framework developers to use these extensions, many decide against it. (XStream https://x-stream.github.io/faq.html is the only i am aware of that actually uses it)

Need Clarity on Java constructors

Okay am just beginning to learn Java and I have a doubt regarding constructors.
isn't constructor just another method with same name as class?? If so Why do we need it? Cant we just use methods?
Constructors have no return type.
They are used for instantiating a class.
They can be called from subclass using Super keyword.
Their name must be same as it's classname
Constructors are called on object creation. You can initialize stuff in other methods of course but then you'd have to call them explicitly.
You don't need to write a constructor. But if you want to do things to ready your object, you put in in your constructor.

Is the Method object equivalent to the Command object in the Command design pattern?

I've just discovered about the existence of the Method class in Java.
Is an instance of this class equivalent to an instance of a Command class in the context of the Command design pattern?
If not, what are this class' practical uses?
Is an instance of this class equivalent to an instance of a Command class in the context of the Command design pattern?
No, absolutely not: Method class is part of reflection feature of Java. Command pattern, on the other hand, is language-agnostic, so it can be implemented in any language, including ones that lack reflection capabilities.
The practical use of the Method class is to access methods of classes to which you do not have access at compile time. You can load a class by name, grab its method object - also by name, and perform an invocation.
With this said, it does not mean that you couldn't implement something that behaves like the command pattern using reflection. In fact, you could make your implementation more flexible by eliminating compile-time dependency on your code. For example, you could build a system that take plugins, and requires that plugin classes implement a particular method. Rather than shipping to plugin writers an interface with the signature of the method, you could tell them that as long as their class implements the method that you need, the plugin is going to be accepted. At runtime you would be able to discover the proper method through reflection, and call user code without compile-time dependencies on either side.
This class, as well as the class Field, class Class, are all part of reflection API. This API is used to provide access to object in an indirect way.
The first idea behind reflection was to allow an object to describe itself. For instance an IDE could display all properties of an object for debugging, RAID development and so on.
If reflection is still used that way, it's also used today to discover dynamically the structure of an object or a class and "act on" it without explicitly knowing it : to change the values of its fields or invoke one its methods.
For instance, if you know class A, you can invoke the method m() of A this way :
A a = new A();
a.m();
With reflection, without knowing class A explicitly, you could :
Object a = A.getDeclaredConstructors()[0].newInstance();
Method m = a.getClass().getMethod("m");
m.invoke(a, null);
In the second case, you can imagine a more generic mechanism where you discover methods or fields and invoke them or change their values without knowing them in advance.
So, to answer directly your question, it has nothing to do with the Command design pattern.

java constructor best practice

What is the advantage of having constructor simillar to the one mentioned below:-
class A{
public A(A a){}
public A(){}
}
If you mean the one with the parameter, there's no reason for having that at all, given that it completely ignores the parameter, and there's already another constructor with the same effect.
If you can give a more realistic example, we may be able to give more useful information...
A(A a){/*do something*/} Can be helpful as copy constructor.
As others have said, you have a copy constructor. There are a number of reasons why you may want a copy constructor. Some of those are:
You can provide an alternative to the clone method. (Which is implemented via the Clonable interface.)
Copy constructors are easily implemented.
You can use another constructor to build the copy (by extracting data from the original object and forwarding to a regular constructor).
Check out the link I added to this post for more information about copy constructors and why you would want to use them (if you need them).
There is no advantage unless you need to have a copy constructor. I would suggest using the clone() method if this object should be clonable rather than using a copy constructor semantic.
You're question is very unclear, but basically if you hava a class, that has a constructor, that takes an instance of the same class, then you have a copy constructor. i.e. a constructor that creates a new instance with the same internal values as the original.
Edit -- assuming of course that your constructor does something other than just create a new instance.
It could also be useful in a number of delegation-based design patterns such as decorator or proxy etc.
Providing a default constructor might still be considered good practice, especially in scenarios where dependency injection or serialization are considered.

Categories

Resources