I need to create new instances of many classes. I'm using reflection but when I make c.newInstance(), the classes without 'empty parameter constructor' throws an java.lang.InstantiationException.
Now, how can i do to create instances of every classes ?
I know that i can use c.getConstructor(Class).newinstance(params) to create instances of classes that doesn't have 'empty parameter constructor', but i do not know the params of each classes.
One more thing, all those classes extend from another class called ParentClass, so one workaround that i could use is to include some code in the ParentClass that force the child classes to implement an 'empty parameter constructor', but don't know how to do this.
Thanks in advance !
You can call Class.getConstructors() to get all the constructors for a given class.
On each Constructor, you can call Constructor.getGenericParameterTypes() to learn which parameters it expects.
JavaDoc for Class
JavaDoc for Constructor
You can't. There's no way to "require" a parameterless constructor and have it enforced by the compiler, and by definition to create an instance of a class you must provide it with the necessary parameters, or otherwise you'll wind up with an object that violates the class contract (because it is not initialized properly).
The proper way to enforce this at a code level is with an object factory and interfaces. I'm presuming that you're having to use reflection because you don't know about the types at compile time; In this case, there should also be a "Factory" which knows how to produce instances of each type. This factory should be built/compiled with the type in question, so that it is aware of and can invoke the proper constructor. The Factory then implements an interface which your code is aware of, such as "ObjectFactory", that allows you to delegate to the factory for instantiating objects. You would then have some method which an object factory can use to register as being responsible for whatever types it can instantiate.
In the code that ships with the classes you're trying to create:
static {
FactoryRegistry.register(TypeA.class, new TypeAFactory());
}
And in your code:
Class<?> unknownClass = ...;
Object obj = FactoryRegistry.getFactory(unknownClass).newInstance();
(where you have a Factory interface that TypeAFactory implements and specifies the newInstance method)
You don't know what unknownClass is or how to instantiate it, but if the code that came with that class registered a factory, you can query for that factory and ask it to create the object for you. If unknownClass is really TypeA.class, then the registry will return the TypeAFactory that was registered to create objects.
Alternatively, you can just require that the authors of any code your framework is loading dynamically include an argument-less constructor. It's not rigidly enforced, but can be easier for authors to implement.
There are two reflective methods for creating instances of classes: java.lang.reflect.Constructor.newInstance() and Class.newInstance()
Class.newInstance() can only invoke the zero-argument constructor, while
Constructor.newInstance() may invoke any constructor, regardless of the number of parameters.
Related
I am a beginner in Java and the book that I use to learn it seems to have cryptic examples and sentences that completely confuse me.
I understand what interfaces are and how/where to apply the concept in real world. But what are Factory Methods? The term "factory method" is ambiguous (JavaScript has a different meaning for that) so I am providing the snippet that the book has, in order to make my question clear. Here is the code:
interface Service {
void method1();
void method2();
}
interface ServiceFactory {
Service getService();
}
The Service interface is just a normal interface. ServiceFactory interface looks like a normal interface but it is a "Factory Method". What's that? What does it solve and why I should use them?
A factory method is simply a method that encaspulate the creation of an object. Instead of using the new operator as you normally would for creating an instead of a Service, in your example, you're using the factory method on some object.
ServiceFactory sf = new ServiceFactoryImpl();
// factory method
Service s = sf.getService();
To better illustrate the role of the method, it could be called createService instead. Now the method encapsulates the details of the creation of a Service, you can provide many flavors of the methods (by overloading), you can have it return different subclasses depending on the context, or parameters passed to the factory method.
A "factory method" is a method that constructs an object.
More specifically, the term usually refers to a static method that returns an instance of its declaring class (either a direct instance, or an instance of a subclass). In my experience, there are a few cases where that's particularly commonly done:
If you need to have multiple different constructors, using factory methods lets you give them appropriate names (whereas calls to different constructors can only be distinguished by the argument-types, which aren't always obvious at a glance).
If you need to have a few different implementations of a single abstract class that serves as the entry-point, the factory method can instantiate the appropriate subtype.
If you need any sort of caching logic or shared instances, the factory method can handle that, returning an already-existing instance if appropriate.
If you need to do some work with side effects, a factory method can be named in such a way that it's more clear what those side effects are.
So, your example doesn't really involve a "factory method" IMHO, but you can cheat a bit and describe getService() as one. (Rather, I would just describe ServiceFactory as a "factory" at leave it at that.) The benefits of ServiceFactory.getService() are the same as those of a factory method, plus the usual benefits of having an instance instead of a static method.
I essentially have a main class that uses interfaces to call other classes which contain members. I am supposed to mock the interfaces that this (concrete) main class uses to call the other classes. The purpose of this is to create a mocked getMember() method for these other classes that would be cumbersome to implement. We only need to ensure, for now, that the main class behaves as expected, given certain return values from the getMember() method.
The only way I see this being possible right now is by passing mock instances of the classes that implement those interfaces.
I'm very sorry if this seems like a stupid question, but I just cannot find an answer to my question by reading this assignment, documentation or via search engines.
Try this:
AnInterface anInterfaceMock = Mockito.mock(AnInterface.class);
//Set your properties here if you want return an specific object.
Member member = new Member();
Mockito.when(anInterfaceMock.getMember()).thenReturn(member);
YourMainClass yourMain = new YourMainClass();
yourMain.setAnInterfaceMock(anInterfaceMock);
yourMain.testMethod(); // call the method you wan to test. This method internal implementation is supposed to call anInterfaceMock.getMember()
Mockito.verify(anInterfaceMock).getMember();
UPDATE:
After the info about the main class not having a way to force the chose interface to mock, it seems like a work to PowerMockito. But posting the code of your main class would help a lot.
Is it your main class that creates the instances of its dependencies (that implement those interfaces that you mentioned)?
If possible you'd better change the main class to follow the Dependency Injection pattern. Then you'll supply our main class with its dependencies via constructor or via setters. Those dependencies can be mocks for testing or the true implementations in the production code.
Modifying the guilhermerama's example a bit.
YourMainClass yourMain = new YourMainClass(anInterfaceMock);
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.
I've got an interface MigrateScenario with its methods. I also have its implementation MigrateScenarioImpl. The instance of MigrateScenarioImpl is being serialized and then passed as a byte[] to some web-service. On the service side, when I try to do this:
Object obj = (new ObjectInputStream(digitalObject.getContent().getInputStream())).readObject();
MigrateScenario mgrScenario = (MigrateScenario) obj;
and what I get is that MigrateScenarioImpl class is missing in the classpath. The obj variable contains that object and the interface should blindly ask for the corresponding methods, since the object "knows itself" how to execute them. However, when I add the MigrateScenarioImpl to the classpath, then all works fine. Am I missing something here?
Would appreciate any help, thanks!
Knowing just the interface doesn't help the JVM know what to do. It needs the Impl to know what to actually do, not just what methods are available.
You can't deserialize a class without having that class known to the classloader (e.g. by being on the classpath). The code for the class itself is not serialized, it is expected to be known on the other end.
When you deserialize the object, Java needs to instantiate and initialize in an instance of the class. Interfaces cannot be instantiated, so Java must instantiate the implementation class. The serialization of a class contains instance data (the values of non transient instance variables), not the code of implemented methods, so there are no methods for the interface to point to.
As part of a larger project, I am attempting to achieve something that I'm not sure is possible, so am eager to see if anyone has any suggestions!
The overall system:
As a whole, my system should be able to be provided with a JUnit test class, that matches some provided interface. Classes will be then given that do not implement this interface, but need to be checked to see if they would be able to (a.k.a. if they implement all necessary methods). If so, some transformation should take place such that the JUnit test class can be run against it.
So far I have implemented:
- A package that loads other classes given a path and name, using URLClassLoader
- A package that runs a JUnit test case and returns the results, using JUnitCore
The problem:
1. At first, how could I run the JUnit test against a class that does implement the interface when the test is designed to match the interface? How do I (at runtime) dictate that the instance being tested by the interface is the loaded class?
Is it possible to then extend this, such that I could i) verify that it does match the interface (I assume using Reflection to check for corresponding methods?) and then ii) modify that class such that it can be tested using the JUnit test class?
Thanks for any advice that might help towards part of this problem. I appreciate my description may be lacking, so please comment if you have any extra information that would help you give any answer!
You can do everything you want with the reflection API. It sounds like you should start with the tutorial, and then come back here for specific questions. Given a Class object you can check if it implements a given interface, create an instance of it, and then treat it like any other class.
Edit: I don't think I got that from your question, but in that case you are looking for the Proxy part of the reflection API.
how could I run the JUnit test against
a class that does implement the
interface when the test is designed to
match the interface
Since you have the class you can use the isAssignableFrom method offered by the class such that
Class loadedJunitClass = clazz;
MyInterface impl = null;
if(MyInterface.class.isAssignableFrom(loadedJunitClass )){
impl = (MyInterface) loadedJunitClass.newInstance();
}
For the second question, you can check each method and see 1. If there exists a method with the same method name as defined in the interface, 2. If the method return type is the same from the interface and 3. If the method parameter types and length are the same. Of course 2 and 3 can be tricky to get right.
At that point I would just create an instance of that interface (anonymous or a private class), create a newInstance of that matching class. And invoke the methods through reflection within the interface's methods.
Now that is how you can get it done with reflection. I am not advicating reflection as you can imagine :)
For the first part of your question; if you have the loaded Class instance for the class you want to test you can construct one with newInstance() if it has a default constructor, or via the getConstructor methods if you need to pass parameters. You should be able to get this Class instance from the class loader.
For the second part. You should be able to check the public methods via getMethods() (again on the Class instance) then look through the returned array for the methods you want. There are methods on the Method class that will return information about parameters, exceptions and return type to verify they are what you require.
However, I am pretty certain it is not possible to modify the class at runtime to add the interface. It might be possible by modifying the byte code, but I don't know about that.
An alternative would be to write your test to call all method via reflection, then it doesn't matter what the type of the object is just that it has the right methods (which you've already checked).
If you want to make arbitrary class to implement given interface at runtime if its public API matches the interface, you have several options in Java. Creating java.lang.Proxy to bridge the target class, exposing YourInterface is the easiest way.
YourInterface i = (YourInterface) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
new Class[]{YourInterface.class},
new InvocationHandler() {
#Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
//run method on your target class here using reflection
}
});
You can also use mixins in AspectJ or subclass your target class using CGLIB and add interface at runtime. But the proxy approach is not that hard-core to implement.