I'm using Dictionary class to localize my application, since I want my texts to be files outside of the application, so I can change them without the need to compile the app again.
To be able to get the strings, I created class StringIdentifiers, that had all the methods like:
public String minute(){
return getString("minute");
}
The method getString() basically just used a Dictionary to get the string from a JSON included into the page.
I then created subclass called Language, where I had some more logic (checking what language to use etc.). It all worked flawlessly, I used the Language subclass to access the Strings. Even in UIBinder.
Since there are more and more texts now, I decided to split these methods into separate classes. But since in Java I cannot do multiple inheritance, I decided to do it via interfaces. So instead of StringIdentifiers I created interfaces like: LoginTexts, MenuTexts, EventLogTexts etc. In these interfaces I specified default methods to get the appropriate strings. The Language class implements all the interfaces and also the getString() method.
Now it all works fine, I get instance of the Language class, I can use methods from the interfaces in the code, no errors.
BUT when it comes to UI binder, it doesn't show errors in editor, but at compilation it tells:
[ERROR] Could not find no-arg method named minute in type
com.company.project.client.locale.Language
Does this mean, that UI binder is not able to see inherited default method from the interfaces? Really? I mean in the Java code, it is working normally.
Im experiencing the same issue, however, after searching I discovered this clever work-around written by Jos31fr: https://github.com/gwtproject/gwt/issues/9629
Define the interface assuming that GWT supports default methods.
In the class implementing the interface, redefine the default method as a call to the super-class.
import com.google.gwt.user.client.ui.TextBox;
public class TestTextBox extends TextBox implements TestInterface {
public void setFoo(String bar) {
TestInterface.super.setFoo(bar);
}
}
Related
It is possible in plain Java to override a method of a class
programmatically at runtime (or even create a new method)?
I want to be able to do this even if I don't know the classes at compile time.
What I mean exactly by overriding at runtime:
abstract class MyClass{
public void myMethod();
}
class Overrider extends MyClass{
#Override
public void myMethod(){}
}
class Injector{
public static void myMethod(){ // STATIC !!!
// do actual stuff
}
}
// some magic code goes here
Overrider altered = doMagic(
MyClass.class, Overrider.class, Injector.class);
Now, this invocation...
altered.myMethod();
...would call Injector.myMethod() instead of Overrider.myMethod().
Injector.myMethod() is static, because, after doing "magic"
it is invoked from different class instance (it's the Overrider),
(so we prevent it from accessing local fields).
You can use something like cglib for generating code on-the-fly
In java6 has been added the possibility to transform any already loaded class. Take a look at the changes in the java.lang.instrument package
For interfaces there is java.lang.reflect.Proxy.
For classes you'll either need a third-party library or write a fair bit of code. Generally dynamically creating classes in this way is to create mocks for testing.
There is also the instrumentation API that allows modification of classes. You can also modify classes with a custom class loader or just the class files on disk.
I wrote an article for java.net about how to transparently add logging statements to a class when it is loaded by the classloader using a java agent.
It uses the Javassist library to manipulate the byte code, including using the Javassist compiler to generate extra bytecode which is then inserted in the appropriate place, and then the resulting class is provided to the classloader.
A refined version is available with the slf4j project.
If I got it right, the main problem that concerns you is how to pass a static method delegate (like in C#), through the instance interface method.
You can check this article: A Java Programmer Looks at C# Delegates (archived), which shows you how to get a reference to your static method and invoke it. You can then create a wrapper class which accepts the static method name in its constructor, and implements your base class to invoke the static method from the instance method.
I'm stuck with a rather peculiar design problem. I'm using a Java ORM, and have defined one of my model classes as follows:
class User extends Model {
// . . .
}
Now, there are more models, and I'd like them all to support data validations. The idea is simple: As each setter method is called, an internal ArrayList of errors keeps getting populated.
Now, the mechanism of error handling is exactly the same for all the model classes. I can envision the following interface:
public interface ErrorReportable {
ArrayList<String> errors = new ArrayList<String>();
boolean hasErrors();
ArrayList<String> getErrors();
void resetErrors();
}
Now I have a problem: All the methods are abstract, which means I'll have to provide an implementation for all of them in my classes. This is sad, because all these methods are going to be implemented in exactly the same way. Ideally, this would've been another class I would've neatly inherited from, but sadly, there's no multiple inheritance in Java.
My next option is use default methods in interfaces, but here the problem is the errors field, which will become static whereas I need a regular field for each instance.
It looks like the only solution is composition, but then I'll have to have a hasErrors() method on User, which will go return this.error_obj.hasErrors(). This is fine, but not really neat in my opinion as I'm having to write things twice.
How can I do better?
I think it would be better for the model classes to only expose List<Error> validate() method, and to have a stand-alone validator that validates all the fields and collects the errors.
That way, the collected messages are not part of the model's state, you have explicit control over when will the validation happen, you're preferring composition (which is almost always a good thing), and the only method you need to implement in model class is the entity-specific validation.
If you ever need to add any cross-field validations, it will also be probably quite easy to extend this design to also perform those alongside with field validations.
If I get your need right, I would implement an own Model-class, that implements all neceaasary Interfaces and extends the Model-ancestor, but still is Abstract.
Then all your normal model-classes inherit from your abstract model-class to get the implementation for the interface and also the inheritance from the model-class (2nd Generation would that be). Any framework checking with 'instance of' will still check true for the later model-class.
The abstract class does not even have to have any abstract methods/members, but it should stay abstract to prevent direct instanciating from that class.
public abstract class myModel extends Model implements ErrorReportable{ ... }
public class User extends myModel { ... }
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.
How is it helpful to use anonymous class if every time we have to define a class while invoking a constructor of an interface.Wouldn't it be more better to simple use a generic type instead?
Anonymous classes is frequently used in GUI applications. When you only need to declare and create object of a class at the same time, it can make the code more precise.
Here is an example:
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
Anonymous classes are not defined every time they are instantiated. They get compiled into bytecode just like other classes, with a name e.g. MyEnclosingClass$1. See this post for more information: How are anonymous classes compiled in Java?
Tangentially, reflection can be used to identify them at runtime using Class.isAnonymousClass().
It depends on the situation; in some cases it will be better to use an anonymous class, and in others, it will be better to use a concrete class that implements the required interface.
If you believe that you'll need to provide the same anonymous class definition repeatedly, it will likely save you time to pass an instance of a concrete class that implements the required interface.
The Java language provides anonymous class syntax as a convenience.
To give you just a taste, here's a quick example from my own experience: Having lists backed by functions.
In general, anonymous classes have (among others) the following uses:
Suppose you want to have an object (an instance, not a class) whose behavior depends on some value available at runtime. Without anonymous classes, you can do this by setting fields (or calling state-changing methods) - but you can't have different code executing. Now, true, you could have bunch of switch() statements in your class' method code - but that completely decouples the definition of the behavior from its context. Another way you could go is to use a named subclass, but that's a lot of code, and it creates a noun you don't really want to exist.
Functional Programming! Until Java 8 comes along, anonymous functions are just about the only way you can pass around functions, which are not first-class citizens in Java. With those, you can perform many neat and elegant tricks like my example above.
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.