I have a RPC service with the following method:
public List<Serializable> myMethod(TransactionCall call) {...}
But I get a warning when this method is analyzed, and then the rpc call fails
Analyzing 'my.project.package.myService' for serializable types
Analyzing methods:
public abstract java.util.List<java.io.Serializable> myMethod(my.project.package.TransactionCall call)
Return type: java.util.List<java.io.Serializable>
[...]
java.io.Serializable
Verifying instantiability
(!) Checking all subtypes of Object which qualify for serialization
It seems I can't use Serializable for my List... I could use my own interface instead (something like AsyncDataInterface, which implements the Serializable interface) but the fact is that my method will return a list custom objects AND basic objects (such as Strings, int....).
So my questions are:
Is it a standard behavior? (I can't figure out why I can't use this interface in that case)
Does anyone have a workaround for that kind of situation?
When passing objects across RPC call's its a good practice to declare concrete parameter types in the RPC interface. If for some reason you cannot use concrete class in the RPC interface try to be as specific as possible.
This is because the GWT compiler while emitting javascript has to take into account all possible variants of List in the compilation unit. This includes all the classes extending List and Serializable interface in the class path. The permutations can be huge, which will effect your compile time as well as the application download size.
So the best approach is to define your interface as
public ArrayList<YourType> myMethod(TransactionCall call) {...}
rather than
public List<Serializable> myMethod(TransactionCall call) {...}
That way compiler has to generate compilation units for ArrayList and YourType extensions only. The benifit is in faster compile times and smaller compiled javascript files, hence faster downloads of your application.
In case you have to return a wide range of unrelated objects in your RPC call, try creating a wrapper class and return object of the wrapper class with the return value wrapped. Use the wrapper class in the RPC method definition. Resist the urge to declare the wrapped field as Object or Serializable, you will negate all serialization benefits you gained by using a wrapper. Instead you can define a Wrapper interface and a small set of Wrapper implementation for each concrete type you wish to return through your RPC call.
You might want to check that serialization policy file isn't the source of the problem.
Quote from GWT documentation:
However, there is one condition to enable support for java.io.Serializable in the new GWT RPC system.
RPC now generates a serialization policy file during GWT compilation. The serialization policy file contains a whitelist of allowed types which may be serialized. Its name is a strong hash name followed by .gwt.rpc. In order to enable support for java.io.Serializable, the types that your application will send over the wire must be included in the serialization policy whitelist. Also, the serialization policy file must be deployed to your web server as a public resource, accessible from a RemoteServiceServlet via ServletContext.getResource(). If it is not deployed properly, RPC will run in 1.3.3 compatibility mode and refuse to serialize types implementing java.io.Serializable.
I don't see the point of defining List<Serializable> as the return value. The type Serializable provides no additional information in the service API declaration. GWT will make the serialization check at runtime anyway.
In your case, where the list elements have no common ancestor other than Object, I would use List<?>.
Related
I am perplexed. I read some threads on stack-overflow regarding marker interfaces in JAVA.
On this thread it is written as:
Marker interfaces aren't 'identified by the JVM' at all. They're identified by the Java code that is interested in them, for example ObjectOutputStream, via the instanceof operator.
Then in comments, it is asserted that:
The implementation in ObjectOutputStream checks if the object has implemented the Serializable interface, if yes perform wirteObject(objectToBeSerialized). So even we can write a marker interface and write a code that checks if an object is an instance of that marker interface and take appropriate action on it then.
On another thread it is written as:
Only Serializable will mark an object as being compatible with Java's built-in serialization machinery.
You can create other empty interfaces, but they won't mean the same thing. Each interface is distinct, even if it defines the same set of methods.
So my question is can we make classes that use serialization without implementing corresponding JAVA's built in interface?
Or is it a special interface that is mandatory to be implemented?
(Asumme, I don't want to use instance of)
As per the book "Effecive java" what does the statement "The class of the object returned by a static factory method need not even exist
at the time the class containing the method is written." means in following paragraph:
The class of the object returned by a static factory method need not even exist
at the time the class containing the method is written. Such flexible static factory
methods form the basis of service provider frameworks, such as the Java Database
Connectivity API (JDBC). A service provider framework is a system in which
multiple service providers implement a service, and the system makes the implementations
available to its clients, decoupling them from the implementations
As per the book "Effecive java" what does the statement "The class of
the object returned by a static factory method need not even exist at
the time the class containing the method is written." means in
following paragraph:
A good way to explain what is meant by this sentence is to consider the EnumSet type, which is a class in the java.util package.
EnumSet is an abstract class without any accessible constructors. In order to get an EnumSet instance, the programmer uses one of its static factory methods, eg. EnumSet.of( ... ). For example:
Set<MyEnum> s = EnumSet.of(MyEnum.FIRST_CONSTANT);
The object returned by the of() method does not have an implementation type of EnumSet. Rather, the implementation type depends on the MyEnum class. If MyEnum has 64 or fewer constants, then the type of the object returned by of() is RegularEnumSet. If MyClass has more than 64 constants, the type of the object returned is JumboEnumSet. The actual type of the object returned, however, is of no interest to the programmer. All he or she cares about is getting some type of object that adheres to the EnumSet contract.
Now, let's say that, oh, five years later the Java language architects decide that it would be important to have another EnumSet implementation type, say, just for example, a cached enum implementation for classes with very large numbers of constants (more than 1024). They write this class to follow the EnumSet contract and call it:
final CachedEnumSet extends EnumSet {
:
:
}
Even though CachedEnumSet didn't exist when EnumSet was written, the fact that the use of static factories enabled a contract-based implementation system enabled the Java architects to add this new implementation years later.
Now, when a client invokes EnumSet.of(), he or she could get a RegularEnumSet object, a JumboEnumSet object, or the new CachedEnumSet object, but they wouldn't care because the object they get is still a subtype of EnumSet and is governed by its contract.
A factory method is generally going to be returning a class that implements an interface (or extends a class, same result either way). But the actual class to be returned may be defined dynamically. In that case, the class to be returned doesn't need to exist when the factory method is written.
May be easiest by example. The JDBC example is something like DriverManager - you provide a database connection URL. From that URL, the DriverManager needs to figure out which class to return. If you're using an Oracle database, it creates an Oracle driver class (which implements the JDBC APIs), even though DriverManager doesn't know anything about Oracle specifically.
As a general case, let's say our factory method returns interface AA. The implementation of the factory method might read a configuration file that defines the class to create, then use reflection to create that class at runtime. The defined class just needs to exist in the CLASSPATH. The factory method knows how to create it, but the implementation hadn't existed at the time the factory method was written.
There are lots of everyday examples where this sort of thing occurs: JDBC providers, custom logging appenders, XML providers.
TL;DR
Can I use Java serialization/deserialization using Serializable interface, ObjectOutputStream and ObjectInputStream classes, and probably adding readObject and writeObject in the classes implementing Serializable as a valid implementation for Prototype pattern or not?
Note
This question is not to discuss if using copy constructor is better than serialization/deserialization or not.
I'm aware of the Prototype Pattern concept (from Wikipedia, emphasis mine):
The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
And from this Q/A: Examples of GoF Design Patterns in Java's core libraries, BalusC explains that prototype pattern in Java is implemented by Object#clone only if the class implements Cloneable interface (marker interface similar to Serializable to serialize/deserialize objects). The problem using this approach is noted in blog posts/related Q/As like these:
Copy Constructor versus Cloning
Java: recommended solution for deep cloning/copying an instance
So, another alternative is using a copy constructor to clone your objects (the DIY way), but this fails to implement the prototype pattern for the text I emphasized above:
avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword)
AFAIK the only way to create an object without invoking its constructor is by deserialization, as noted in the example of the accepted answer of this question: How are constructors called during serialization and deserialization?
So, I'm just asking if using object deserialization through ObjectOutputStream (and knowing what you're doing, marking necessary fields as transient and understanding all the implications of this process) or a similar approach would be a proper implementation of Prototype Pattern.
Note: I don't think unmarshalling XML documents is a right implementation of this pattern because invokes the class constructor. Probably this also happens when unmarshalling JSON content as well.
People would advise using object constructor, and I would mind that option when working with simple objects. This question is more oriented to deep copying complex objects, where I may have 5 levels of objects to clone. For example:
//fields is an abbreviation for primitive type and String type fields
//that can vary between 1 and 20 (or more) declared fields in the class
//and all of them will be filled during application execution
class CustomerType {
//fields...
}
class Customer {
CustomerType customerType;
//fields
}
class Product {
//fields
}
class Order {
List<Product> productList;
Customer customer;
//fields
}
class InvoiceStatus {
//fields
}
class Invoice {
List<Order> orderList;
InvoiceStatus invoiceStatus;
//fields
}
//class to communicate invoice data for external systems
class InvoiceOutboundMessage {
List<Invoice> invoice;
//fields
}
Let's say, I want/need to copy a instance of InvoiceOutboundMessage. I don't think a copy constructor would apply in this case. IMO having a lot of copy constructors doesn't seem like a good design in this case.
Using Java object serialization directly is not quite the Prototype pattern, but serialization can be used to implement the pattern.
The Prototype pattern puts the responsibility of copying on the object to be copied. If you use serialization directly, the client needs to provide the deserialization and serialization code. If you own, or plan to write, all of the classes that are to be copied, it is easy to move the responsibility to those classes:
define a Prototype interface which extends Serializable and adds an instance method copy
define a concrete class PrototypeUtility with a static method copy that implements the serialization and deserialization in one place
define an abstract class AbstractPrototype that implements Prototype. Make its copy method delegate to PrototypeUtility.copy.
A class which needs to be a Prototype can either implement Prototype itself and use PrototypeUtility to do the work, or can just extend AbstractPrototype. By doing so it also advertises that it is safely Serializable.
If you don't own the classes whose instances are to be copied, you can't follow the Prototype pattern exactly, because you can't move the responsibility for copying to those classes. However, if those classes implement Serializable, you can still get the job done by using serialization directly.
Regarding copy constructors, those are a fine way to copy Java objects whose classes you know, but they don't meet the requirement that the Prototype pattern does that the client should not need to know the class of the object instance that it is copying. A client which doesn't know an instance's class but wants to use its copy constructor would have to use reflection to find a constructor whose only argument has the same class as the class it belongs to. That's ugly, and the client couldn't be sure that the constructor it found was a copy constructor. Implementing an interface addresses those issues cleanly.
Wikipedia's comment that the Prototype pattern avoids the cost of creating a new object seems misguided to me. (I see nothing about that in the Gang of Four description.) Wikipedia's example of an object that is expensive to create is an object which lists the occurrences of a word in a text, which of course are expensive to find. But it would be foolish to design your program so that the only way to get an instance of WordOccurrences was to actually analyze a text, especially if you then needed to copy that instance for some reason. Just give it a constructor with parameters that describe the entire state of the instance and assigns them to its fields, or a copy constructor.
So unless you're working with a third-party library that hides its reasonable constructors, forget about that performance canard. The important points of Prototype are that
it allows the client to copy an object instance without knowing its class, and
it accomplishes that goal without creating a hierarchy of factories, as meeting the same goal with the AbstractFactory pattern would.
I'm puzzled by this part of your requirements:
Note: I don't think unmarshalling XML documents is a right
implementation of this pattern because invokes the class constructor.
Probably this also happens when unmarshalling JSON content as well.
I understand that you might not want to implement a copy constructor, but you will always have a regular constructor. If this constructor is invoked by a library then what does it matter? Furthermore object creation in Java is cheap. I've used Jackson for marshalling/unmarshalling Java objects with great success. It is performant and has a number of awesome features that might be very helpful in your case. You could implement a deep copier as follows:
import com.fasterxml.jackson.databind.ObjectMapper;
public class MyCloner {
private ObjectMapper cloner; // with getter and setter
public <T> clone(T toClone){
String stringCopy = mapper.writeValueAsString(toClone);
T deepClone = mapper.readValue(stringCopy, toClone.getClass());
return deepClone;
}
}
Note that Jackson will work automatically with Beans (getter + setter pairs, no-arg constructor). For classes that break that pattern it needs additional configuration. One nice thing about this configuration is that it won't require you to edit your existing classes, so you can clone using JSON without any other part of your code knowing that JSON is being used.
Another reason I like this approach vs. serialization is it is more human debuggable (just look at the string to see what the data is). Additionally, there are tons of tools out there for working with JSON:
Online JSON formatter
Veiw JSON as HTML based webpage
Whereas tools for Java serialization isn't great.
One drawback to this approach is that by default duplicate references in the original object will be made unique in the copied object by default. Here is an example:
public class CloneTest {
public class MyObject { }
public class MyObjectContainer {
MyObject refA;
MyObject refB;
// Getters and Setters omitted
}
public static void runTest(){
MyCloner cloner = new MyCloner();
cloner.setCloner(new ObjectMapper());
MyObjectContainer container = new MyObjectContainer();
MyObject duplicateReference = new MyObject();
MyObjectContainer.setRefA(duplicateReference);
MyObjectContainer.setRefB(duplicateReference);
MyObjectContainer cloned = cloner.clone(container);
System.out.println(cloned.getRefA() == cloned.getRefB()); // Will print false
System.out.println(container.getRefA() == container.getRefB()); // Will print true
}
}
Given that there are several approaches to this problem each with their own pros and cons, I would claim there isn't a 'proper' way to implement the prototype pattern in Java. The right approach depends heavily on the environment you find yourself coding in. If you have constructors which do heavy computation (and can't circumvent them) then I suppose you don't have much option but to use Deserialization. Otherwise, I would prefer the JSON/XML approach. If external libraries weren't allowed and I could modify my beans, then I'd use Dave's approach.
Your question is really interesting Luiggi (I voted for it because the idea is great), it's a pitty you don't say what you are really concerned about. So I'll try to answer what I know and let you choose what you find arguable:
Advantages :
In terms of memory use, you will get a very good memory consumption by using serialization since it serializes your objects in binary format (and not in text as json or worse: xml). You may have to choose a strategy to keep your objects "pattern" in memory as long as you need it, and persist it in a "less used first persisted" strategy, or "first used first persisted"
Coding it is pretty direct. There are some rules to respect, but it you don't have many complex structures, this remains maintainable
No need for external libraries, this is pretty an advantage in institutions with strict security/legal rules (validations for each library to be used in a program)
If you don't need to maintain your objects between versions of the program/ versions of the JVM. You can profit from each JVM update as speed is a real concern for java programs, and it's very related to io operations (JMX, memory read/writes, nio, etc...). So there are big chances that new versions will have optimized io/memory usage/serialization algos and you will find you're writing/reading faster with no code change.
Disadvantages :
You loose all your prototypes if you change any object in the tree. Serialization works only with the same object definition
You need to deserialize an object to see what is inside it: as opposed to the prototype pattern that is 'self documenting' if you take it from a Spring / Guice configuration file. The binary objects saved to disk are pretty opaque
If you're planning to do a reusable library, you're imposing to your library users a pretty strict pattern (implementing Serializable on each object, or using transient for dields that are not serializable). In addition this constraints cannot be checked by the compiler, you have to run the program to see if there's something wrong (which might not be visible immediately if an object in the tree is null for the tests). Naturally, I'm comparing it to other prototyping technologies (Guice for example had the main feature of being compile time checked, Spring did it lately too)
I think it's all what comes to my mind for now, I'll add a comment if any new aspect raises suddenly :)
Naturally I don't know how fast is writing an object as bytes compared to invoking a constructor. The answer to this should be mass write/read tests
But the question is worth thinking.
There are cases where creating new object using copy constructor is different from creating new object "in a standard way". One example is explained in the Wikipedia link in your question. In that example, to create new WordOccurrences using the constructor WordOccurrences(text, word), we need to perform heavyweight computation. If we use copy constructor WordOccurrences(wordOccurences) instead, we can immediately get the result of that computation (in the Wikipedia, clone method is used, but the principle is the same).
Why do Java introduces some interface which has no methods defined in it? For example Cloneable, Serializable, Type and many more.
Second thing : In Class.class package there is one method defined registerNatives() without body and is called from static block but Class.class is not abstract but is final. Why so?
and Why Java need some method without body to be called from static block.?
Why do Java introduces some interface which has no methods defined in it?
This are called Tagged or Marker interface. These are not used for any use or operation. These methods are used to tag or marking a class. So that you can determine whether someclass is a child of those classes.
about the second question
If you look closely you can see the declaration is
private static native void registerNatives();
So registerNatives is a native methods.
So what is native methods. If you see this so question
The method is implemented in "native" code. That is, code that does
not run in the JVM. It's typically written in C or C++.
Native methods are usually used to interface with system calls or
libraries written in other programming languages.
So these methods are loaded from native codes. So you don't need to declare the body of the methods but still they are not abstract as they have their implementation from native codes.
Marker interface is used as a tag to inform a message to the java compiler so that it can add special behavior to the class implementing it. Java marker interface has no members in it.
The purpose of Marker interfaces is to force some kind of functionality in the classes by providing some functionality to a class if it implements the marker interface.
Read Java Marker Interface also see What is the use of marker interfaces in Java?
For the first one you are actually asking for a Marker Interface. Marker Interfaces are by design not supposed to add anything to behavior but support only polymorphic transformation of the object. e.g. Serializable makes an object capable of streaming across JVM boundaries. Marker interfaces follow the 'universal type substitution' philosophy.
For second one, you are actually asking for JNI. Java doesnot implement all its code in Java form. I mean in classes and code that follow Java syntax. Some time or the other you need to drill down to the native platform API to implement something for that API. e.g. sockets and TCP communication. It is this feature of Java that actually makes it platform independent. The JVM runtime is platform dependent as it uses platform based native methods and dll or .so libraries to implement and integrate with the platform. We as programmers call the high level Java SDK API calls.
One of the "clean" features of the Java programming language is that it mandates a separation between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Java to specify the behavior of derived classes.
Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known as marker interfaces. Some examples of marker interfaces in the Java API include:
java.lang.Cloneable
java.io.Serializable
java.util.EventListener
Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category based on their purpose. For example, all classes that implement the Cloneable interface can be cloned (i.e., the clone() method can be called on them). The Java compiler checks to make sure that if the clone() method is called on a class and the class implements the Cloneable interface. For example, consider the following call to the clone() method on an object o:
SomeObject o = new SomeObject();
SomeObject ref = (SomeObject)(o.clone());
If the class SomeObject does not implement the interface Cloneable (and Cloneable is not implemented by any of the superclasses that SomeObject inherits from), the compiler will mark this line as an error. This is because the clone() method may only be called by objects of type "Cloneable." Hence, even though Cloneable is an empty interface, it serves an important purpose.
registerNatives()
native method are implemented in JVM itself.
What does the registerNatives() method do?
Why Java need some method without body to be called from static block.?
This is called from static block because we need to call this method when classes are loaded and not when it's instance is created.
Please provide some basic information of how TypeLiteral in Google Guice or Java EE is used, It will be very helpful if it would be explained using a simple code, thanks in advance
The purpose of TypeLiteral in Guice is to allow you to bind classes and instances to generic types (with type parameters specified) avoiding the problems stemming from the fact that generics are not reified in Java, i.e. from the fact that erasure hides the difference between SomeInterface<String> and SomeInterface<Integer> at runtime. TypeLiteral allows the value of a generic parameter survive erasure by creating an ad hoc subclass of the generic type.
Example usage of TypeLiteral:
bind(new TypeLiteral<SomeInterface<String>>(){})
.to(SomeImplementation.class);
This binds a parameter of type SomeInterface<String> to SomeImplementation class.
For some background information have a look at this blog post on super type tokens and then this one on type literals.
Like anything in Guice - modularity, reusability, and removal of boilerplate are core concepts of all utilities.
Of course, anything you do in Guice can be mimicked in Java - at the cost of lots of boilerplate So... the real question is :
How can we USE TypeLiterals to write more modular/reusable components ?
The power of TypeLiterals in Guice is that it allows you to refernce implementations of a service without defining what that service is.
Lets start with a simple list in a program where we have many types of lists that are processed differntly :
List<String> myStringList = new ArrayList<String>();
Now, how should I process these Strings ? At runtime, there is no way to "know" that its a String list. So, often times I might create a factory, like so , that gets processing objects for me :
ProcessorFactory.get(String.class).process(myStringList);
Thus, I might use a factory (with a bunch of if/else or case statements) to define processors for different data types. My constructor, for the object which uses these processors, and which needs access to various Processor Implementations, might look like this :
public MyClass(Processor<String> strProcessor, Processor<Integer> intProcessor)P
{
//Simple enough, but alot of boiler plate is required to launch this constructor.
}
//and to invoke
new MyClass(PRocessorFactory.get(....), ProcessorFactory.get(...));
All good so far... Until we realize that there is a better way :
In the Guice world, I can forget about writing this factory - rather, I can explicitly BIND classes to processors. The advantage of this is that there are no static dependencies - the class which needs to USE processor implementations DOES NOT need any static dependency on a factory -rather, the classes are directly injected. Thus, I can easily define a class which uses complex dependencies, without having to build a factory aware class builder... Thus, I have far less boilerplate :
#Inject
public MyClass(Processor<String> implStr, Processor<Integer> implInt)
{
//Now , this method will work magically, because Guice is capable of
//Using the loaded modules, which define bindings between generics and their implementations
}
//Elsewhere I simply define a single guice module that does the binding, and make sure to load it before my application launches.
There is a good tutorial on this with interface implementations and binding examples, here : http://thejavablog.wordpress.com/2008/11/17/how-to-inject-a-generic-interface-using-guice/
This is a way how guys bypass generics erasure in java. You need it, when you want ot bind some implementation to parametrized(generic) interface. Found some usage in Guice docs:
bind(new TypeLiteral<PaymentService<CreditCard>>() {})
.to(CreditCardPaymentService.class);
This admittedly odd construct is the way to bind a parameterized type. It tells Guice how to honor an injection request for an element of type PaymentService. The class CreditCardPaymentService must implement the PaymentService interface. Guice cannot currently bind or inject a generic type, such as Set; all type parameters must be fully specified.
The TypeLiteral class is a workaround for the fact that you cannot have class literals for generic types. The API doc of Binder (this is from Google Guice, but the Java EE class of the same name has exactly the same purpose) gives an example for how it's used:
bind(new TypeLiteral<PaymentService<CreditCard>>() {})
.to(CreditCardPaymentService.class);
This specifies that any auto-injected reference of type PaymentService<CreditCard> will be implemented by the concrete class CreditCardPaymentService, leaving the option for PaymentService<Coupon> to be implemented by a different class. Without TypeLiteral, this would not be possible because the Java compiler will accept PaymentService<CreditCard>.class, only PaymentService.class.
Note that this also requires the use of anonymous subclasses (the {} after new TypeLiteral<PaymentService<CreditCard>>()) in order to work around type erasure.
I'll simplify the answer/reason for the existence of TypeLiteral<> in GUICE:
if java allows you to write:
bind(FooInterface<String>.class).to(FooImplementation.class);
then you are done, there is no need for TypeLiteral<>
but java has this "Type Erasure" thing for generics, so FooInterface<String>.class won't even get complied.
So you use:
bind(new TypeLiteral<FooInterface<String>>() {}).to(FooImplementation.class);
"new TypeLiteral<Interface>() {}" will create some anonymous class and new an object out of it. You can imagine that object knows everything about the tpye info of the Interface, so GUICE use that object to perform the DI magic.