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.
Related
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.
In some places where a class hierarchy is present and the top most base class is an abstract class there is a static getInstance() method in the abstract class. This will be responsible for creating the correct sub-class and returning it to the caller. For example consider the below code.
public class abstract Product {
public static Product getInstance(String aCode) {
if ("a".equals(aCode) {
return new ProductA();
}
return ProductDefault();
}
// product behaviour methods
}
public class ProductA extends Product {}
public class ProductDefault extends Product {}
In Java, java.util.Calendar.getInstance() is one place this pattern has been followed. However this means each time a new subclass is introduced one has to modify the base class. i.e: Product class has to be modified in the above example. This seems to violate the ocp principle. Also the base class is aware about the sub class details which is again questionable.
My question is...
is the above pattern an anti-pattern ?
what are the draw-backs of using the above pattern ?
what alternatives can be followed instead ?
The interface is not an anti-pattern. But the way you've implemented it is rather poor ... for the reason you identified. A better idea would be to have some mechanism for registering factory objects for each code:
The Java class libraries do this kind of thing using SPIs and code that looks reflectively for "provider" classes to be dynamically loaded.
A simpler approach is to have a "registry" object, and populate it using dependency injection, or static initializers in the factory object classes, or a startup method that reads class names from a properties file, etcetera.
No it's not. It's more like factory method pattern http://en.wikipedia.org/wiki/Factory_method_pattern. E.g. Calendar.getInstance();. JDK is full of such examples. Also reminds of Effective Java Item 1: Consider static factory methods instead of constructors
There are a number of separate issues here.
getInstance is probably going to be a bad name. You explicitly want a new object you can play around with. "Create", "make", "new" or just leave that word out. "Instance" is also a pretty vacuous word in this context. If there is sufficient context from the class name leave it out, otherwise say what it is even if that is just a type name. If the method returns an immutable object, of is the convention (valueOf in olden times).
Putting it in an abstract base class (or in an interface if that were possible) is, as identified, not the best idea. In some cases an enumeration of all possible subtypes is appropriate - an enum obviously and really not that bad if you are going to use visitors anyway. Better to put it in a new file.
Anything to do with mutable statics is wrong. Whether it is reusing the same mutable instance, registration or doing something disgusting with the current thread. Don't do it or depend (direct or indirectly) on anything that does.
Based on the feedback i introduced a new ProductFactory class that took care of creating the correct Product. In my case the creation of the correct product instance depends on an external context (i've put the product code for the purpose of simplicity.. in the actual case it might be based on several parameters.. these could change over time). So having a Product.getInstance() method is not that suited because of the reasons outlined in the question. Also having a different ProductFactory means in the future.. Product class can become an interface if required. It just gives more extensibility.
I think when the creation of the object doesn't depend on an external context.. like in the case of Calendar.getInstance() it's perfectly ok to have such a method. In these situations the logic of finding the correct instance is internal to that particular module/class and doesn't depend on any externally provided information..
I'm developping a server application in Java. The server need two type of server classes. These classes have some methods in common, the code in these methods is exactly the same. So i create an abstract super-class containing all the shared code, and both classes are inheriting it. But, there is some part of the code that need to be precised by subclasses. I mean that the superclass "rely" on subclasses methods.
Here is a purified example of what i mean:
public abstract class AbstractServer
{
public void loadConfig(String configPath)
{
//Load the configuration file.
//This code is exactly the same for subclasses.
}
public void startRMI(int port)
{
//Create an empty RMI registry.
//This part also need to be identical.
//Here' where the superclass "rely" on subclasses.
fillRegistry(); //Call the method overwritten by subclasses.
}
/**
Bind remote objects in the RMI registry
*/
protected abstract void fillRegistry(); //This method will be overriten by subclasses.
}
I feel that it's really bad to make it like that, but i can't find another cleaner way to do it.
So, what i want is some advice on how i could make it better.
Thanks, and sorry for my bad english.
Your approach is just fine. Stick with it buddy.
I feel your 'philosophical need' to understand it. Base class 'relying' on the subclass is fine as long as the base class is abstract. It knows that some things have to be registered at this point, but it doesn't have the faintest clue about what exactly to be registered. So the high-level process is encoded in the base class with 'holes' that can be plugged in by the derived class. The high level process and the position of the 'hole' itself is valuable and this justifies the implementation of the base class. The derived classes just follow the fundamental OO principle of 'coding by difference' and plugs the 'holes'.
Looks about right to me after your edits (assuming that you left out the Exception throwing part for readability) :)
All three methods would need to raise exceptions in a real world case.
Super class is inherited by sub-class. You can write methods in super class which you want to make common and leave it untouched. For the other part of code which you want it to be overwritten by sub classes define other set of methods in super class. write methods in sub-classes also. when u call method from sub-class u can put to call super-class method's
in short u have to write methods in sub class to over write the methods of superclass.
I would also make sure that your superclass is actually abstract. In this snippet it isn't. Overall though, looks decent.
Also consider declaring any instance variables in your superclass that classes that extend it will need as well.
First, there is nothing wrong with requiring subclasses' implementation in abstract (base) classes. It's just something that should not get abused, IMO. However, if I had to avoid it, I would make the ServerClass not abstract at all, and define every method of it. Instead, I would create RegistryFactory classes and pass them to the ServerClass :
class ServerClass {
public void startRMI(int port, RegistryFactory rf) {
// ...
rf.fillRegistry(this);
}
}
interface RegistryFactory {
/**
* Implement this method
*/
public void fillRegistry(ServerClass server);
}
public class RMIRegistryFactory implements RegistryFactory {
public void fillRegistry(ServerClass server) { /* ... */ }
}
Or something like that.
Your approach is fine, but it needs a simple improvement to make it perfect - make the startRMI() method final:
public final void startRMI(int port) {
fillRegistry();
}
This way you will prevent that someone overrides it (maybe because of not knowing that everything in startRMI() should be reused and that only fillRegistry() has to be customized).
Your solution generally matches the template method design pattern:
The template method is a method in a superclass, usually an abstract
superclass, and defines the skeleton of an operation in terms of a
number of high-level steps. These steps are themselves implemented by
additional helper methods in the same class as the template method.
The helper methods may be either abstract methods, for which case
subclasses are required to provide concrete implementations, or hook
methods, which have empty bodies in the superclass. Subclasses can
(but are not required to) customize the operation by overriding the
hook methods. The intent of the template method is to define the
overall structure of the operation, while allowing subclasses to
refine, or redefine, certain steps. (Wikipedia)
Given the above, the method startRMI() is a template method which defines the skeleton of an operation by using a number of high-level steps (in your case it's only one step but this doesn't make a difference). The method fillRegistry() in your example is a high-level step - it's defined as an abstract method in the superclass and has a concrete implementation in the superclasses.
On the other side, if you would override the method startRMI() in a subclass, this would not be OK anymore. That's why you should make it final to avoid confusion - this way someone who creates a subclass will know that he must implement fillRegistry() (since it's abstract) but should not change the implementation of startRMI (since it's final).
Since this is a commonly used design pattern, I wouldn't worry at all if this solution is OK, a lot of people are doing it like that and everyone who knows design patterns will recognize it, I think it feels very natural even for developers who don't know the design pattern.
Assuming I have a class like
public class FooImpl
{
public void bar(){};
}
Is there a way to create its interface at runtime?
e.g.
public interface Foo
{
public void bar();
}
I have been looking into Javasssist and the truth is it's reflection that I'm interested in using the interface for (as Esko Luontola and Yishai stated)
So I want an interface that specifies a subset of the original class' methods to make a proxy from.
I came to realize there are more things to be concerned about like
Should you reuse that interface or create a new one each time?
The proxy class is effectively a new instance of type java.lang.reflect.Proxy, which might cause implications depending on the use case.
The last point made me wonder on how some frameworks manage to handle this, do they deep copy the object? do they encapsulate the proxy inside the original instance?
So maybe it's just easier (though maybe not as elegant) to require for the client code to create the interface for the class.
You can do it with some bytecode manipulation/generation during class loading, for example using ASM, Javassist or similar, maybe also AspectJ.
The important question is, why would you need to do that? No normal code can use the class through its interface, because the interface does not exist at compile time. You would either need to generate the code that uses the interface or use reflection - but in that case you might as well use the original class. And for the interface to be useful, you should probably also modify the original class so that it implements the generated interface (this can be done with the libraries I mentioned).
You can look at something like Javassist to create the class. You would go over the class with Class.getMethods() and have to implement the bytecode at runtime for the interface, and then use the Proxy class to bridge the interface and implementation.