Construct a subclass from a superclass - java

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);
}
}

Related

How to store static data about a class to

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.

Create a stub of 3rd party Java library

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

Can we write a function in Java that takes another function signature as a parameter and executes it? [duplicate]

This may be something common and trivial, but I seem to be having trouble finding a concrete answer. In C# there is a concept of delegates, which relates strongly to the idea of function pointers from C++. Is there a similar functionality in Java? Given that pointers are somewhat absent, what is the best way about this? And to be clear, we're talking first class here.
The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
and method references:
list.sort(MyClass::isGreaterThan);
You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.
public interface IFunction {
public void execute(Object o);
}
This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
As an example say we have a collection of numbers and you would like to add 1 to every element.
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});
You can use reflection to do it.
Pass as parameter the object and the method name (as a string) and then invoke the method. For example:
Object methodCaller(Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
// Catch the exceptions
}
And then use it as in:
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");
Of course, check all exceptions and add the needed casts.
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.
This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.
To achieve similar functionality you could use anonymous inner classes.
If you were to define a interface Foo:
interface Foo {
Object myFunc(Object arg);
}
Create a method bar which will receive a 'function pointer' as an argument:
public void bar(Foo foo) {
// .....
Object object = foo.myFunc(argValue);
// .....
}
Finally call the method as follows:
bar(new Foo() {
public Object myFunc(Object arg) {
// Function code.
}
}
Java8 has introduced lambdas and method references. So if your function matches a functional interface (you can create your own) you can use a method reference in this case.
Java provides a set of common functional interfaces. whereas you could do the following:
public class Test {
public void test1(Integer i) {}
public void test2(Integer i) {}
public void consumer(Consumer<Integer> a) {
a.accept(10);
}
public void provideConsumer() {
consumer(this::test1); // method reference
consumer(x -> test2(x)); // lambda
}
}
There is no such thing in Java. You will need to wrap your function into some object and pass the reference to that object in order to pass the reference to the method on that object.
Syntactically, this can be eased to a certain extent by using anonymous classes defined in-place or anonymous classes defined as member variables of the class.
Example:
class MyComponent extends JPanel {
private JButton button;
public MyComponent() {
button = new JButton("click me");
button.addActionListener(buttonAction);
add(button);
}
private ActionListener buttonAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handle the event...
// note how the handler instance can access
// members of the surrounding class
button.setText("you clicked me");
}
}
}
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
We have a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array did not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to it's inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:
http://code.google.com/p/lambdaj/wiki/Closures
Relative to most people here I am new to java but since I haven't seen a similar suggestion I have another alternative to suggest. Im not sure if its a good practice or not, or even suggested before and I just didn't get it. I just like it since I think its self descriptive.
/*Just to merge functions in a common name*/
public class CustomFunction{
public CustomFunction(){}
}
/*Actual functions*/
public class Function1 extends CustomFunction{
public Function1(){}
public void execute(){...something here...}
}
public class Function2 extends CustomFunction{
public Function2(){}
public void execute(){...something here...}
}
.....
/*in Main class*/
CustomFunction functionpointer = null;
then depending on the application, assign
functionpointer = new Function1();
functionpointer = new Function2();
etc.
and call by
functionpointer.execute();

Java - Restricting by what a method can be called

I have methods set to public because they must be called by an exterior class, but I only ever want them called by one or two methods. Being called by other methods could create bugs in my program. So, in order to prevent me from accidentally programming around my own methods, I have been doing stuff like this within the methods of which I want to restrict callers:
if(trace.length<2){
throw new Exception("Class should not call its own function.");
}else if(trace[1].getClassName()!=desiredClassName || trace[1].getMethodName()!=desiredMethodName){
throw new Exception(trace[1].getClassName()+"\" is invalid function caller. Should only be called by "+desiredClassName+"->"+desiredMethodName+".");
}
Is there something else I should be doing, or should I just not forget how my program works?
You should be using visibility to restrict calling - making a method public (or for that matter, javadocing it) is not going to work unless you have dicipline (and you control the callers too). From your description, you are neither.
What you can do is make the class package private, and put it in the same package as the two callers of that class. As long as you have a proper package structure, this can work. E.g.:
Your class that should only be called by A and B:
package thepackage.of.a.and.b;
//imports here
class CallableByAB {
public void methodA(){}
public void methodB(){}
}
A:
package thepackage.of.a.and.b;
public class A {
/*...other code here */
new CallableByAB().methodA();
/*...other code here */
}
B:
package thepackage.of.a.and.b;
public class B {
/*...other code here */
new CallableByAB().methodB();
/*...other code here */
}
other classes cannot call new CallableByAB() or import it. hence, safety.
This seems like a very brittle solution to a problem you should not need to solve.
In this particular case you may not suffer too greatly in future maintenance, just a couple of methods with these kind of special guards. But imagine trying to apply such logic to many methods across a large code base - it's just not a tenable thing to do. Even in your case you are effectivley writing code that cannot be reused in other contexts.
The fact that you need to do this surely reflects some kind of mis-design.
I infer that you have some kind of stateful interface whose state gets fouled up if called unexpectedly. Ideally I would want to make the interface more robust, but if that just cannot be done: If there are particular methods that should use this interface can you move those methods to a specific class - maybe an inner class of the current objtec you have - and have a handle visible only in this class?
private Class TheLegalCaller {
private RestrictedCallee myCallee = new RestricatedCallee() ; // or other creation
public void doOneThing() { myCallee.doOne(); }
public void doOtherThing() } myCallee.doOther(); }
}
Now the downside with this is that it only pushes the problem up a level, if you randomly use TheLegalCaller in the wrong places then I guess you still have an issue. But maybe by making the restriction very visible it aids your memory?
Try using access rules.
http://groups.google.com/group/google-web-toolkit/browse_thread/thread/90c424dc44db523e
I found a very simple way to do that, but requires some coding methodology:
class AllowedCaller {
private Object key;
public boolean getKey(){
return key;
}
public void allowedCallingMethod(RestrictedAccessClass rac){
this.key = rac;
rac.restrictedMethod();
this.key = null;
}
}
class RestrictedAccessClass{
public void restrictedMethod(){
if(allowedCallerInstance.getKey() != this){
throw new NullPointerException("forbidden!");
}
// do restricted stuff
}
}
I think it could be improved to prevent multithread simultaneous access to restrictedMethod().
Also, the key could be on another class other than AllowedCaller (so RestrictedAccessClass would not need to know about AllowedClass), and such control could be centralized, so instead of a single key, it could be an ArrayList with several object keys allowed at the same time.

How do I extend a java class that is instantiated by another class?

Given two java classes, A and B, where A is usually instantiated via B, such as:
A myA = B.createA();
Can I create a subclass of A (let's call it SubA) and somehow have it be instantiated by the B.createA() method?
(Note that I cannot modify A and B....)
I know that not all instances of A are instances of SubA, thus I cannot do this:
SubA mySubA = B.createA();
Similarly, I cannot cast it like this either:
SubA mySubA = (SubA) (B.createA());
for the same reason -- it will get a ClassCastException.
Am I being dense and forgetting something fundamental, or is there no way to do this?
(Late addition: I'm so sorry, I should have mentioned that A and B have roughly 50 methods each, and all I want to do is add a single property to SubA, along with a getter and a setter. I'd really rather not implement all 50 of A's methods to invoke the corresponding method in the superclass's object.)
It sounds like like what you'd really like is to modify the behavior of both the original A and B. In that case, you could try extending both classes (where the extension of B is purely to specify a slightly different factory method for creating SubAs).
class SubA extends A {
/** This is the one special aspect of SubA justifying a sub-class.
Using double purely as an example. */
private double specialProperty;
public double getSpecialProperty() { return specialProperty; }
public void setSpecialProperty(double newSP) { specialProperty = newSP; }
public SubA() {
super();
// Important differences between SubAs and As go here....
// If there aren't any others, you don't need this constructor.
}
// NOTE: you don't have to do anything else with the other methods of
// A. You just inherit those.
}
class SubB extends B {
// Purely for the purposes of a slightly different factory method
public A createA() {
return new SubA();
}
// Or if you need a static method
// (this is usually instead of the first choice)
public static A createA() {
return new SubA();
}
}
Note that at this point, you could create one of your SubB factory objects and make it look like the original B like so:
B myNewB = new SubB();
A myA = myNewB.createA();
Or, if you're using the static factory instead, it isn't quite as close a match (but it's close).
A myA = SubB.createA();
Now, if you really need to do something with the sub-property, you'll have access to it via the child interface. I.e., if you create the object like so:
SubA mySubA = SubB.createA();
mySubA.setSpecialProperty(3.14);
double special = mySubA.getSpecialProperty();
Edit to discuss "Late addition":
At this point, your SubA object should be exactly what you want. It will inherit the 50 methods from the parent (A) and you can add your additional property to the child, plus the getter and setter. I changed the code above to illustrate what I mean.
This is usually done via a proxy:
class SubA extends A {
private A proxiedClass;
public SubA(A a) {
proxiedClass = a;
}
public int anyMethodInA() {
return proxiedClass.anyMethodInA();
}
}
...
SubA mySubA = new SubA(B.createA());
Doing this manually is rather verbose, so most people use some kind of a AOP library (like AspectJ) to only intercept method calls they are interested in.
You could create a wrapper around it, with SubA having a constructor that takes A as the parameter.
Like this:
SubA mySubA = new SubA(B.createA());
Since all instances of SubA are instances of A, you could then assign it to your existing A variable and override any necessary methods.
A myA = new SubA(B.createA());
I can't think of any other clean way of doing it.
If you are just wanting to add a field to A without object oriented such as changing behaviour, you could add it as an "external field". Use a WeakHashMap to map from instance of A onto the field value (just so long as the field value doesn't directly or indirectly reference A or you'll have an object life time contention issue):
private static final Map<A,FieldType> map =
new java.util.WeakHashMap<A,FieldType>(); // thread-safe from 1.6, IIRC
public static FieldType getField(A a) {
return map.get(a);
}
public static void setField(A a, FieldType value) {
map.set(a, value);
}
Really we should be using WeakIdentityHashMap, but it doesn't exist in the Java library!

Categories