Why does a CustomFieldSerializer need static methods? - java

You use a CustomFieldSerializer to define custom serialisation and deserialisation for an object.
It's ostensibly easy to define custom serialization for your class Xxx:
create a class called Xxx_CustomFieldSerializer that extends CustomFieldSerializer<Xxx>,
implement abstract methods serializeInstance and deserializeInstance, and optionally instantiateInstance.
This generates a gazillion compile errors that boil down to the following:
subtype Custom Field Serializer 'Xxx_CustomFieldSerializer' does not define a deserialize method: 'public static void deserialize(SerializationStreamReader reader,Xxx instance)' (reached via Xxx)'
It wants you to create static methods that do exactly what the implemented methods do. Obviously one delegates to the other, but it means you can't extract out all of this boilerplate for similar types Xxx.
Why? Is this just left over from an old version of GWT or something? Is there a way to avoid having to write all the extra stuff?

Thanks to Thomas Broyer for finding this. It's just a limitation in GWT.
See: com.google.gwt.user.rebind.rpc.CustomFieldSerializerValidator
See: http://code.google.com/p/google-web-toolkit/issues/detail?id=7331&thanks=7331&ts=1335182609

Related

Is there any way to get Class from reflection?

Is there any way to get Class from reflection?
What i want to do is, I have implemented custom Serializer for hazelcast-3.2.3. and I don't want to write separate Serializer for each class(whom object I need to store in Hcast).
I want this
class TestSerializer<T> {
Class<T> classType;
Public Test(){
classType = T.someway() //if there is any method to get that;
}
}
Because I'm configuring my Serializer in hazelcast.xml i cant pass Class in constructor parameters.
I assume you're really asking how to get the class of the generic type T during runtime, not just a class.
The easiest way to do it is to pass it as an argument to the constructor but if you really, really want to do it with reflection, you can use a trick that eg. Jackson uses which relies on anonymous sub classes. To do this, read up on how TypeReference works, especially Super Type Tokens
I might, of course, be wildly off here on what you want to do. Please correct me if I am :)
Your TestSerializer cannot get that type internally due to type erasure. That information has to be provided externally.
This means you'll have to refactor how you do it through configuration.

Could I define a 'Interface' for 'Class' instead of 'Object' in java?

We know 'interface' in java provide a common way to access objects who implementing it, but i wonder if there's a way like interface which not just for accessing the object's method, but also for accessing the class's method(static method). I want to use it to invoke an array of different classes's static factory method. Does java provide something like it?
No.
But you can implement the pattern you describe easily with an ordinary object interface, then a set of classes that just wrap the static methods you wish to call through to.
If your intentions is to call static method of an implementing class using Interface reference, the answer is No. static members belong to class only, so you will always need a Class type reference (actually it should be the class name) to access them.
With interfaces you can only point to what you have declared in it.
No, there's no kind of "interface for static methods" in Java.
(Aside from anything else, how would you expect to specify the class in question? Even generics wouldn't help here due to type erasure.)

Framework to populate common field in unrelated classes

I'm attempting to write a framework to handle an interface with an external library and its API. As part of that, I need to populate a header field that exists with the same name and type in each of many (70ish) possible message classes. Unfortunately, instead of having each message class derive from a common base class that would contain the header field, each one is entirely separate.
As as toy example:
public class A
{
public Header header;
public Integer aData;
}
public class B
{
public Header header;
public Long bData;
}
If they had designed them sanely where A and B derived from some base class containing the header, I could just do:
public boolean sendMessage(BaseType b)
{
b.header = populateHeader();
stuffNecessaryToSendMessage();
}
But as it stands, Object is the only common class. The various options I've thought of would be:
A separate method for each type. This would work, and be fast, but the code duplication would be depressingly wasteful.
I could subclass each of the types and have them implement a common Interface. While this would work, creating 70+ subclasses and then modifying the code to use them instead of the original messaging classes is a bridge too far.
Reflection. Workable, but I'd expect it to be too slow (performance is a concern here)
Given these, the separate method for each seems like my best bet, but I'd love to have a better option.
I'd suggest you the following. Create a set of interfaces you'd like to have. For example
public interface HeaderHolder {
public void setHeader(Header header);
public Header getHeader();
}
I'd like your classes to implement them, i.e you's like that your class B is defined as
class B implements HeaderHolder {...}
Unfortunately it is not. Now problem!
Create facade:
public class InterfaceWrapper {
public <T> T wrap(Object obj, Class<T> api) {...}
}
You can implement it at this phase using dynamic proxy. Yes, dynamic proxy uses reflection, but forget about this right now.
Once you are done you can use your InterfaceWrapper as following:
B b = new B();
new IntefaceWrapper().wrap(b, HeaderHolder.class).setHeader("my header");
As you can see now you can set headers to any class you want (if it has appropriate property). Once you are done you can check your performance. If and only if usage of reflection in dynamic proxy is a bottleneck change the implementation to code generation (e.g. based on custom annotation, package name etc). There are a lot of tools that can help you to do this or alternatively you can implement such logic yourself. The point is that you can always change implementation of IntefaceWrapper without changing other code.
But avoid premature optimization. Reflection works very efficiently these days. Sun/Oracle worked hard to achieve this. They for example create classes on the fly and cache them to make reflection faster. So probably taking in consideration the full flow the reflective call does not take too much time.
How about dynamically generating those 70+ subclasses in the build time of your project ? That way you won't need to maintain 70+ source files while keeping the benefits of the approach from your second bullet.
The only library I know of that can do this Dozer. It does use reflection, but the good news is that it'll be easier to test if it's slow than to write your own reflection code to discover that it's slow.
By default, dozer will call the same getter/setters on two objects even if they are completely different. You can configure it in much more complex ways though. For example, you can also tell it to access the fields directly. You can give it a custom converter to convert a Map to a List, things like that.
You can just take one populated instance, or perhaps even your own BaseType and say, dozer.map(baseType, SubType.class);

Does 'extends Object' have a purpose or is it redundant?

Following a tutorial on the internet regarding Soap development with Java, I found this link, with a rather unusual code for myself.
The code:
public class SoapService extends Object {
/** Creates new SoapService */
public SoapService() {
}
/** This is the SOAP exposes method
*/
public String sayGreeting(String name)
{
return "Hello "+name;
}
}
What's with the 'extends Object' syntax ? I've never encountered this kind of syntax (only on Generics).
Does this syntax has any purpose or is 'plain dumb' ?
Unless the Object class is not actually the java.lang.Object class (the tutorial does not include the imports, so it's hard to see), the extends Object is redundant.
All objects in Java implicitly extend Object, so I'd say it's redundant.
All classes extend Object implicitly anyway so it's just redundant coding having no impact.
Looks a bit like generated code - it's extra effort for a source code generator to omit the "extends" clause if it is not needed, especially if the generator is template-based.
It just means it inherits directly from the Object class. Here is more about inheritance in Java.
No. It's just explicitly doing something that is implicit.
It's unneeded. Every class in Java extends Object at some level. Leave it out, unless you need to clarify something specific.
Extends clause is optional as stated in Java Language Specification. If it is omitted, the class is derived from java.lang.Object. It is just a matter of coding style to write it or not to write it in this case. Usually it is omitted.
It is silly code. Every class in Java extends an Object class. No need to type this explisitly
There is one possibility and that is the person who made it don't want you to extend any classes. You can always do a workaround of course but that is the only thing I can come up with that makes sense.
I think it's redundant.
In Junit source code:
public class TestFailure extends Object {}
I don't know why this class extends Object.
My vote, plain dumb - but then I only play with Java...
But any class inherits from the Object Class as far as I know...
It is legal but useless boilerplate. Everything extends Object so the language spec allows you to leave it out, and it generally should be left out (some writers of coding standards disagree).
The situation is the same in generics (extends Object is implicit and redundant), it is just that for some reason (I have seen some claim early buggy Generics implementations had issues with the ? wildcard) it has caught on a bit more there.
As a matter of fact, it does not seem to be simply redundant, especially when working in the JWS webservices environment.
When defining a class for an XML type to be transported over SOAP, I use the wsimport tool to fetch client dependencies from the WSDL, which creates package-local copies of these classes. By explicitly extending Object, one can seamlessly cast between the classes from the two distinct packages.
Not doing so leads to a compilation error when trying to use a class method from package A that expects an argument type of the class in in package A, and passing in an object generated from the equivalent class in package B.
As java is an object oriented language, it supports inheritance which inherits the properties of the another class, for example all java objects inherits from java.lang.Object class.From the above example it is understood that it is the explanation of inheritance. Note that all classes, whether they state so or not, will be inherit from java.lang.Object.
Any class that doesn't explicitly extend another class,implicitly extends Object
all classes extends the java.lang.Object by default. You can see it
here
Why not make it explicit?
I'm for adding it in - not everyone "implicitly" knows that every Java class implicitly extends Object. By writing it explicitly they don't have to guess.

How to create an interface at Runtime

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.

Categories

Resources