My task is to create stubs for a 3rd party Java library that our application will make calls to. My problem is how to define the class of the method "return type" (if that's the correct Java terminology). I don't have access to the full documentation of the 3rd party API, just a list of methods. For now, my stubs just need to return true/false or 1/0, whatever
Here's an example of one method to illustrate. This is what I have been given
OobResponse RequestOobRequest(
String ClientName,
String SecurityLink,
short LenofHHU,
RequestMode RequestMode)
I have no idea what OobResponse or RequestMode are supposed to be, but I should still be able to create stubs, right?
So far, this is all I have.
public class stubber {
public class OobResponse {
public int someVar;
}
public class RequestMode {
public int someVar;
}
public OobResponse RequestOobRequest(
String ClientName,
String SecurityLink,
short LenofHHU,
RequestMode RequestMode)
{
OobResponse oobr = new OobResponse();
return oobr;
}
}
The documentation you have is weird, since variable and method names do not hold Java convention of using camelCase. Also, what you seem to be ordered to do would hold minimal later use. However, the way I understand your problem you could do:
create new package for all classes you will be stubbing. That will be relevant later
actually stub stuff. That is, for every class in the documentation that is not built into java create the class. I assumed that what you wrote is a method declaration (made most sense to me, though it could also be a constructor or whatever), it needs to be a part of some class, I called it "Unknown" below. Replace that name with actual class name.
For your example you would need:
public class RequestMode {
}
public class OobResponse {
}
public class Unknown {
public OobResponse RequestOobRequest(
String ClientName,
String SecurityLink,
short LenofHHU,
RequestMode RequestMode){
return new OobResponse(); // or null, whatever since it is a stub
}
}
Note, that when stubbing you do not create any additional variables (like someVar you tried to add), ONLY what API allows you to access (only classes and public methods within would be a good rule of a thumb). You could also use interfaces instead of classes, it would be cleaner, but there are legitimate reasons not to (when you want a code with new StubbedClass() to compile for example).
Now, in your actual code you (or someone) will be able to use your stubs like the actual library:
public class YourBusinessClass{
public OobResponse getOobByClientName(String clientName){
return new Unknown().RequestOobRequest(clientName,...);
}
}
When you get the actual library you can replace imports from stub package in your actual code that uses it to the actual library package.
That is the only usefull way of using stubs like that I could think of, so I hope that is what you want.
One possibility (academically at least) is to use a facade to the actual 3rd party library. You could probably create a class which has the methods that you need and your main code calls this class in place of the the 3rd party library, include all the methods that you need and return 1/0 etc., when the library is available dispatch the calls to the library from the facade.
However, there is a fair bit of caution, if the actual data model of the library is complex you could end up replicating all of them or their equivalent in your code, if it is not (like simple strings etc.) then this approach would work.
With reference to the comment below for en example, i am adding the following:
Let us say we have a class:
public class Class0{
public String method0(String arg0){return "from Method 0";}
public String method1(String arg0, String arg1){return "from Method 1";}
}//class closing
Now let us say we only have the signature for the above class and not the class itself, then we can do the following (for now):
public Class0Facade{
public String method0(String arg0){return "from Method 0";}
public String method1(String arg0, String arg1){return "from Method 1";}
}//class closing
Rest of your code can use the 'class0Facade' class and go ahead.
When the actual Class0 is available, you would change Class0Facade, in the following way:
public Class0Facade{
protected Class0 deligate;
public Class0Facade(){delegate=new Class0();}
public String method0(String arg0){return delegate.method0(arg0);}
public String method1(String arg0, String arg1){return delegate.method(arg0, arg1);}
}//class closing
Rest ot four code does not need to change
Maybe you could go with classes that extend the stubbed classes:
public class Stubber extends StubbedClass {
public OobResponse RequestOobRequest(
String ClientName,
String SecurityLink,
short LenofHHU,
RequestMode RequestMode) {
OobResponse oobr = new OobResponse();
return oobr;
}
}
If you cant create an OobResponse, you could similarly create a public class OobResponseStub extends OobResponse
Related
Imagine I have an abstract class like this:
public abstract class Device {
public Device(DeviceModel model){
// ...
}
public abstract boolean isBuildable();
}
Then I have an implementation of it that might look like this:
public final class Floor extends Device {
// ...
#Override
public void boolean isBuildable(){
return false;
}
}
Here, each Device subclass returns either true or false to #isBuildable(). But each instance of Floor always returns false. Another implementation of Device may return true. That sounds like a static data : it does not depends on the current instance, but on the type of the Device.
Currently, I'm creating an instance of the class to get its value, as #isBuildable() isn't static. But I think that's poor code design.
So, what I'm trying to achieve here is like creating abstract static method. I've seen this question that doesn't help so much. I would forces the implementation of #isBuildable (this time as static) in all subclasses of Device, so that I can invoke Floor.isBuildable() or something else of the same kind.
Here I can't control all the source, so I can't use reflectivity on that.
Hope you understand this weird question !
If you need to store class-specific (not instance-specific) information, custom annotations may be the way to go.
This require a function using reflection to access that piece of information, which could be overkill in a small project, but should be no problem in a larger framework or similar project.
In Java, static methods cannot override other static methods, so what you want to do is not possible.
Since Java has no real type variables (the type variables used for generics do not survive until run time) you would need an instance anyway to determine which overridden static method to call.
Suppose you have a class Device with two subclasses, Floor and Ceiling, all of which have a method called foo(). Since there are no run-time type variables, T.foo() cannot work, and Device.foo(), Floor.foo() and Ceiling.foo() all specify exactly which method to call.
There are a few solutions/workarounds:
Call the right method through reflection. You will lose any static type checking.
Introduce a companion enum or class which contains the information about your types. For example:
public class DeviceType {
private final boolean buildable;
private DeviceType(boolean buildable) {
this.buildable = buildable;
}
public boolean isBuildable() {
return buildable;
}
}
public class Floor extends Device {
public static final DeviceType DEVICE_TYPE = new DeviceType(false);
...
}
Now you can pass around Floor.DEVICE_TYPE as a kind of representation of the class which contains the information you want.
I'm working on an Android framework (https://www.github.com/IanSwift/jumper) which takes data model classes and uses reflection to update views when they are created or updated. I use a dynamic proxy factory for this, and I currently have the user enter both the real object and an interface that specifies any state changing methods. My question is, is there a way the code could auto generate an interface from the class? It would look something like this.
Class<?> derivedInterface = somehowGetAnInterface(Original.class)
Where original is an instance something like:
public class Original {
String someData;
public void setSomeData(String s) {
someData = s;
}
public String getSomeData() {
return someData();
}
}
And derived interface gets created either at compile time or run time but looks something like this:
public interface OriginalInterface {
public void setSomeData(String s);
public String getSomeData();
}
Eclipse can do this. Select the class name, right click and select Refactor, then select Extract Interface. In the resulting dialog, provide a name for the interface and select the methods to be extracted.
BTW, when I tried this myself, I found an error in your posted code: the reference to someData in getSomeData() should be to a field, not a method.
This is all in the context of JBox2D (in Java). The World class creates Body instances with a function. I'm trying to add a bit more stuff to Body for my application. Body is represented by ComplexClassWithLotsOfAPI in this question.
Here is the generalized question. I am trying to add a bit more functionality to a premade class by extending the class. I hope to do something like this:
class SomeMore extends ComplexClassWithLotsOfAPI{
int myExtraInt;
//A bit more API functions
}
So that I may do this:
SomeMore sm=new SomeMore();
sm.someOldAPI();
sm.butAlsoMyNewAPI();
The problem is that this ComplexClassWithLotsOfAPI is created by another class that I can't modify (the World class in the original context), so I am not simply creating them on my own (otherwise this would work). Since I am stuck having to start with a ComplexClassWithLotsOfAPI, I have been searching for a way to construct a SubClass from a SuperClass, whereas there are many examples of casting a SuperClass to a Subclass (but this is not applicable here). Here is an example of the function that needs to be completed:
public SomeMore create(...){
ComplexClassWithLotsOfAPI ccwlao=myWorld.create(...);
SomeMore sm;
//??
return sm;
}
Alternative to Wrapping?
My original solution was to encase the ComplexClassWithLotsOfAPI into my own class. In order to construct my new class, I simply pass the old class into my new constructor and move on:
class SomeMore{
public ComplexClassWithLotsOfAPI ccwloa;
int myExtraInt;
public SomeMore(ComplexClassWithLotsOfAPI nccwloa){
ccwloa=nccwloa;
myExtraInt=0;
}
//A bit more API functions
}
public SomeMore create(...){
ComplexClassWithLotsOfAPI ccwlao=myWorld.create(...);
SomeMore sm=new SomeMore(ccwlao);
return sm;
//OR more simply
//return new SomeMore(myWorld.create(...));
}
But in order to access the old API, I need to do this:
SomeMore sm=new SomeMore();
sm.ccwloa.someOldAPI();
sm.butAlsoMyNewAPI();
I could just be a bit unreasonable, but this kind of functionality is tedious and adds just that much more complication to something that doesn't need it. I mean, if someone wanted to add a tad more functionality, would they wrap my class into yet another class, and have 3 class heirarchies to go through to get old APIs? Also, it would feel just wasteful to wrap every single API in the old class into my new class (there's a lot of them).
sm.someOldAPIButWrappedInMyClass(); //not desirable
I do not have access to the java files of ComplexClassWithLotsOfAPI, only the compiled class files. I can not simply force my modifications into the old class (and even if I could, I'd prefer not to anyway). I am relatively new to java, so perhaps this is not the best/proper way to do this, but I haven't been able to find an alternative.
Eclipse can build you a delegate class that is a subclass of some class (i.e. Parent) and holds an instance of 'Parent' in a field (called the delegatee) and generates methods that override all the methods in 'Parent' with calls to the same method in the delegatee. You can then add your own methods.
You do this from the context menu, Source option, generate delegate methods. You have to have the subclass and have it extend 'Parent' and have a field of type 'Parent' to let the code generator work.
Here's an example:
/** Example class delegating to a contained variable */
public class DelegatingComparator implements Comparator<String> {
// Delegatee has to be present before letting Eclipse generate
private Comparator<String> delegatee;
/** My own method extends Comparator methods */
public int compareToFoo(String o1) {
return compare(o1, "foo");
}
/** Generated by Eclipse. Source > Generate getters and setters */
public void setDelegatee(Comparator<String> delegatee) {
this.delegatee = delegatee;
}
/** Generated by Eclipse. Source > Generate Delegate Methods */
public int compare(String o1, String o2) {
return delegatee.compare(o1, o2);
}
/** Generated by Eclipse. Source > Generate Delegate Methods */
public boolean equals(Object obj) {
return delegatee.equals(obj);
}
}
public abstract class Master
{
public void printForAllMethodsInSubClass()
{
System.out.println ("Printing before subclass method executes");
System.out.println ("Parameters for subclass method were: ....");
}
}
public class Owner extends Master {
public void printSomething () {
System.out.println ("This printed from Owner");
}
public int returnSomeCals ()
{
return 5+5;
}
}
Without messing with methods of subclass...is it possible to execute printForAllMethodsInSubClass() before the method of a subclass gets executed?
update:
Using AspectJ/Ruby/Python...etc
Would it also be possible to print the parameters? Above code formatted below:
public abstract class Master
{
public void printForAllMethodsInSubClass()
{
System.out.println ("Printing before subclass method executes");
}
}
public class Owner extends Master {
public void printSomething (String something) {
System.out.println (something + " printed from Owner");
}
public int returnSomeCals (int x, int y)
{
return x+y;
}
}
AspectJ can provide this functionality for you, but it's a separate compilation step and some extra libraries involved.
public aspect ServerLogger {
pointcut printSomething ();
before(): printSomething()
{
(Master)(thisJoinPointStaticPart.getTarget()).printForAlMethodsInSubClass();
}
}
The Eclipse Project provides a great implementation of AspectJ that integrates nicely with Eclipse and Maven. There's a boatload of great documentation available for it, and a lot of really good material for it here on StackOverflow.
[update]
To access parameter info, you can use the
thisJoinPoint.getSignature();
method to access information about the function being called if the returned Object is an instance of MethodSignature, you can use Signature.getParameterNames() to access the parameters to the function being called. You'd have to use a bit of reflection to actually get at the values, I think - AspectJ doesn't seem to handle this for you. I'd have to actually do some experimentation to get some working code for you.
To answer the "any other programming language": It's easily possible in Ruby:
class Master
REDEFINED = []
def printForAllMethodsInSubClass
puts 'Printing before subclass method executes'
end
def self.method_added(meth)
if self < Master and not Master::REDEFINED.include? meth
new_name = "MASTER_OVERRIDE_#{meth}".intern
Master::REDEFINED.push meth, new_name
alias_method new_name, meth
define_method(meth) {|*args| printForAllMethodsInSubClass; send(new_name, *args)}
end
end
end
You could also make a proxy declaration method to use in subclasses:
class Master
def printForAllMethodsInSubClass
Printing before subclass method executes
end
def self.master_method(name)
define_method(name) {|*args| printForAllMethodsInSubClass; yield *args}
end
end
class Owner
master_method(:print_something) do
puts "This was printed from Owner"
end
end
(This approach would also translate very naturally to Python decorators.)
This is possible in aspect-oriented programming languages, such as AspectJ.
In Python you can accomplish this using meta classes, here's a small example. You can probably make it more elegantly but it is just to make the point
import types
class PrintMetaClass(type):
def __init__(cls, name, bases, attrs):
# for every member in the class
override = {}
for attr in attrs:
member = attrs[attr]
# if it's a function
if type(member) == types.FunctionType:
# we wrap it
def wrapped(*args, **kwargs):
print 'before any method'
return member(*args, **kwargs)
override[attr] = wrapped
super(PrintMetaClass, cls).__init__(name, bases, attrs)
for attr in override:
setattr(cls, attr, override[attr])
class Foo:
__metaclass__ = PrintMetaClass
def do_something(self):
print 2
class Bar(Foo):
def do_something_else(self):
print 3
In this example, the PrintMetaClass gets in the way of the creation of the Foo class and any of its subclasses redefining every method to be a wrapper of the original and printing a given message at the beginning. The Bar class receives this aspect-like behavior simply by inheriting from Foo which defines its __metaclass__ to be PrintMetaClass.
Metaclasess in OOP:
http://en.wikipedia.org/wiki/Metaclass
Metaclasses in python:
http://www.python.org/doc/essays/metaclasses/
http://www.ibm.com/developerworks/linux/library/l-pymeta.html
Besides aspect oriented programming have a look at Template Method Pattern, http://en.wikipedia.org/wiki/Template_method_pattern.
In short: the parent class have an abstract method, which subclasses have to implement, this abstract method is called by a method in the parent class where put your printouts or whatever necessary statements.
I've come across some code that I can't share here but it declares a method WITHIN the paramter list of another method. I didnt even know that was possible. I dont really understand why its doing that. Can someone please explain to me some possible uses that you as a programmer would have for doing that? (Note: Since I can't show the code I dont expect an in-context explanation just generally)
Related:
What's the nearest substitute for a function pointer in Java?
Did the code look something like this?
obj.someMethod(myVar,3,new FooObject() {
public void bar() {
return "baz";
}
});
If so, then the method is not being passed to the other method as an argument, but rather an anonymous inner class is being created, and an instance of that class is being passed as the argument.
In the example above FooObject is an abstract class which doesn't implement the bar() method. Instead of creating a private class that extends FooObject we create an instance of the abstract class and provide the implementation of the abstract method in line with the rest of the code.
You can't create an instance of an abstract class so we have to provide the missing method to create a complete class defintion. As this new class is created on the fly it has no name, hence anonymous. As it's defined inside another class it's an anonymous inner class.
It can be a very handy shortcut, especially for Listener classes, but it can make your code hard to follow if you get carried away and the in line method definitions get too long.
In Java you can't pass methods as parameters. Could it have been passing not a method, but an anonymnous inner class?
This can be useful for passing behaviours between classes. Google "dependency injection" or "Inversion of control" for more information.
Have you ever seen the Functional Java?
It's a very interesting library that allows you programing like you would do in Scala.
I Wrote about this libs. I confess it is better to use in a more flexible syntax (BGGA closures) like Scala.
Using Functional Java with a high-order function like map on a list we have:
final List<Integer> numbers = list(1, 2, 3, 4, 5);
List<Integer> c = numbers.map(new F<Integer, Integer>() {
public Integer f(Integer arg) {
return arg * arg;
}
});
Another useful lib is lambdaj that offers nice ways to play like in Functional (FP) Programming.
Java has a limited syntax compared to FP languages. But you can still take some advantages of FP style, but you must be creative!
using java.lang.reflect.Method
example
public void callMethod(Method aMethod, int value) throws Exception {
aMethod.invoke(this, value);
}
public void print(Integer value) {
System.out.print(value);
}
public void println(Integer value) {
System.out.println(value);
}
public void demo() throws Exception {
Method println = this.getClass().getMethod("println", Integer.class);
Method print = this.getClass().getMethod("print", Integer.class);
callMethod(println, 10);
callMethod(print, 10);
}
The nearest thing to passing a function pointer in Java is passing an anonymous instance of an abstract class or interface. For example, a generic function type can be encoded in an interface like this:
public interface F<A, B> {
public B f(final A a);
}
You can then expect a method in another method's argument list:
public List<B> map(List<A> as, F<A, B> f) {
...
}
And you can call it with an anonymous instance of that interface:
map(myList, new F<Integer, String>() {
public String f(Integer i) {
return String.valueOf(i);
}
});
There's a library called Functional Java that exploits exactly this idea for great benefit glorious language Java.
It's not, per se, legal syntax in Java. Was it perhaps creating a new instance of an anonymous class?
You can also do something like this:
final Predicate somePredicate = new Predicate<Item>()
{
#Override
public boolean apply(Item item)
{
return item.someProperty().equals(something);
}
}
And use it like this:
List<Item> filteredList = filter(list, somePredicate);
I've done stuff like that before. I've also written methods that use a closure to build and return an anonymous implementation of an interface in a similar way:
Predicate isSomeColor(final Color color)
{
return new Predicate<Shape>()
{
#Override
public boolean apply(Shape shape)
{
return shape.getColor().equals(color);
}
}
}
List<Shape> redShapes = filter(shapes, isSomeColor(Color.RED);
All of this is still anonymous inner classes. Nowhere am I actually naming the class itself, I just have a reference to an instance of the class.
this is called reflection. there is a whole library of objects representing stuff like constructors, methods and such.
you can use it, for instance, in order to call a dynamic method that is determined on runtime.
Yes, declaration of a method within the parameter list of another method can be done. You can check out java.lang.reflect.Method
Using reflection, you retrieve a Method object representing the method you wish to pass as a parameter. Then you can call Method to invoke to make a call to that method.
Moreover, you can refer "Functional programming in the Java language" (http ://www.ibm.com/developerworks/java/library/j-fp.html) which can give you inside-out with examples.
The answers above are varying as to whether or not it is even possible. Is it possible through reflection? Is possible through the use of an anonymous inner class? We need to clarify this.
the closest to a function argument is
an instance of a anonymous class with exactly one method.
Runnable a = new Runnable(){
run(){
System.out.println("hello");
}
}
myMethod(a);
not pointer, but still you can write functions inline with some trick.
check my answer on another thread