DefaultContractResolver: CreateContract vs ResolveContract - serialization

What is difference between CreateContract and ResolveContract methods of an DefaultContractResolver instance?

If you look at the code, you will notice that ResolveContract is the only public method of DefaultContractResolver (not counting the constructor). This method is defined by the IContractResolver interface, which DefautContractResolver implements. It is used to resolve (that is, get or create) the JsonContract for a particular object type.
The DefaultContractResolver uses caching internally. When ResolveContract is called, it first looks in its cache to see if there is already an existing contract for the given type. If so, it returns it; otherwise, it calls the protected CreateContract method to create the contract and add it to the cache.
So, in short, CreateContract is just an implementation detail of DefaultContractResolver, while ResolveContract is the public interface.

Related

Why does ByteBuddy route method delegation to the "wrong" method in this scenario?

I am putting together a very simple ByteBuddy delegate/proxy class.
The intention is (again, very simple) to proxy a class such that any of its non-final, non-private, non-static methods and so forth get routed to equivalent methods on its proxiedInstance field as returned by its getProxiedInstance method. (There should be exceptions made for the usual suspects: equals, hashCode, wait and notify and so on.)
I've set up my proxy class using the subclass strategy. I've also defined two methods, getProxiedInstance and setProxiedInstance, along with a private field named proxiedInstance of the proper type. I've done this using the FieldAccessor.ofBeanProperty() strategy. I've omitted that here for brevity and clarity. The class does in fact contain this field and these two methods.
Then I've defined the method interception like this, statically importing the relevant ElementMatchers methods:
builder
.method(not(isFinal()).and(not(isStatic())).and(not(isPrivate()))
.and((isPublic().and(named("toString")).and(takesArguments(0)).and(returns(String.class)))
.or((not(isDeclaredBy(Object.class)).and(not(named("getProxiedInstance"))).and(not(named("setProxiedInstance"))))))
)
.intercept(MethodDelegation.toMethodReturnOf("getProxiedInstance"));
In English: not final, not static, not private, and either the public String toString() method inherited from Object (or overridden), or any other method not declared by Object.class and not named getProxiedInstance or setProxiedInstance.
Suppose I have a class like this:
public class Frob {
public String sayHello() {
return "Hello!";
}
}
When I create a proxy class for it, instantiate it, and then call toString() on the proxy, I get Hello!.
This suggests to me somehow that the recipe I've quoted above is somehow routing toString() to sayHello().
From reading the MethodDelegation javadocs, it seems that maybe sayHello on the target/delegate object is picked for delegation because it is more specific than the method invoked on the proxy (toString). I guess name matching is lower priority than that.
I think this use case I have is relatively simple. How do I best accomplish it?
The best I could do, which works, but seems perhaps a little clunky or verbose, was this:
builder = builder
.method(not(isDeclaredBy(Object.class))
.and(not(isFinal()))
.and(not(isStatic()))
.and(not(isPrivate()))
.and(not(named("getProxiedInstance")))
.and(not(named("setProxiedInstance"))))
.intercept(MethodDelegation.toMethodReturnOf("getProxiedInstance"))
.method(is(toStringMethod))
.intercept(invoke(toStringMethod).onMethodCall(invoke(named("getProxiedInstance"))));
(toStringMethod is the Method resulting from Object.class.getMethod("toString").)
I think using MethodCall is a better approach to this. MethodDelegation is meant for "catch all proxies" where you inject corresponding dispatchers into what is often a single delegate method, maybe two. Method call is also much more performance since it does not need to do the analysis but just reroutes to a method of a compatible type.

Redis Serialization and Deserialization

I have noticed that some of my serialized objects stored in Redis have problems deserializing.
This typically occurs when I make changes to the object class being stored in Redis.
I want to understand the problem so that I can have a clear design for a solution.
My question is, what causes deserialization problems?
Would a removal of a public/private property cause a problem?
Adding new properties, perhaps?
Would a adding a new function to the class create problems? How about more constructors?
In my serialized object, I have a property Map, what if I change (updated some properties, added functions, etc) myObject, would it cause a deserialization problem?
what causes deserialization problems?
I would like to give you bit of background before answering your question,
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, It uses the following information of the class to compute SerialVersionUID,
The class name.
The class modifiers written as a 32-bit integer.
The name of each interface sorted by name.
For each field of the class sorted by field name (except private static and private transient fields:
The name of the field.
The modifiers of the field written as a 32-bit integer.
The descriptor of the field.
if a class initializer exists, write out the following:
The name of the method, .
The modifier of the method, java.lang.reflect.Modifier.STATIC, written as a 32-bit integer.
The descriptor of the method, ()V.
For each non-private constructor sorted by method name and signature:
The name of the method, .
The modifiers of the method written as a 32-bit integer.
The descriptor of the method.
For each non-private method sorted by method name and signature:
The name of the method.
The modifiers of the method written as a 32-bit integer.
The descriptor of the method.
So, to answer your question,
Would a removal of a public/private property cause a problem? Adding new properties, perhaps? Would a adding a new function to the class create problems? How about more constructors?
Yes, all these additions/removal by default will cause the problem.
But one way to overcome this is to explicitly define the SerialVersionUID, this will tell the serialization system that i know the class will evolve (or evolved) over the time and don't throw an error. So the de-serialization system reads only those fields that are present in both the side and assigns the value. Newly added fields on the de-serialization side will get the default values. If some fields are deleted on the de-serialization side, the algorithm just reads and skips.
Following is the way one can declare the SerialVersionUID,
private static final long serialVersionUID = 3487495895819393L;

Proper use of private constructors

I was reading about private constructor and found a few points that I couldn't understand. It said, if you declare a constructor as private:
That class cannot be explicitly instantiated from another class
That class cannot be inherited
Should be used in classes containing only static utility methods
My first question: Point 2 says the class cannot be inherited. Well, if you declare a class private then it would still satisfy this property. Is it because, if a class is private, it can still be explicitly instantiated from outside by another class?
My second question: I don't understand point 3. If I have a helper class which is full of static methods, I would never have to instantiate that class to use the methods. So, what is the purpose of a constructor in that class which you are never going to instantiate?
Answer for Java
Question 1 You're confusing a private class, with a class that has a private constructor. Private constructors are used mainly for static classes that are not meant to be instatiated (i.e. they just have a bunch of static methods on them).
Question 2 Exactly there is no need for a constructor so you have to explicitly create a private constructor so that it does not get a default constructer that the JVM will provide if none is defined
An empty class with no methods defined will always be given a no argument constructor by the JVM by default
I take java and c++ as an examples (not the best OO languages known, but very popular) - since you are not defining which languge do you mean.
Ad.2. In these languages you must either call superclass constructor explicitly or it is implicitly called for you. From a subclass you cannot call private methods (only public and protected) - this rule applies to constructors as well. This means if the class has only private constructors, there is no way to call one in subclass constructor. So you cannot subclass such class.
Ad. 3. It is just to avoid confusion - since this class is only a container for utility methods, there is no point in instantiating it. This way you can enforce this rule at compile time.

How to decide an object behavior through the web.config?

I want to be able to define in my web.config the type of connexion my object will use to get data (variable) (from an xml or from a databases).
I though about using a Strategie Pattern, but I'm somewhat stuck by the need to write somewhere the name of the class, which I do not want.
Any suggestions?
Additionnal info
I have the interface IContext.
It's implemented in ContextXML and ContextDB.
I have the class Context which has a IContext member (called _context).
The Context class reads (through ContextConfiguration) app.config.
I want _context to be able to be a ContextXML or a ContextDB... or a ContextJSon or any other new class that would implements IContext.
Have you thought about creating a ContextManager class and employing "configuration by convention"?
What I would do, is add a member getName to your IContext interface - this just returns a nice human-readable string for each implementation - as simple as "ContextXML" for your ContextXML class.
When your ContextManager (probably a Singleton, BTW) starts up, it scans a known directory for IContext implementations, instantiating them by reflection (or some other mechanism, I'm not familiar with VB.Net but I'm sure there's a way), and placing them in a collection.
Now when you are building up Context objects, you can ask your ContextManager for a suitable IContext - either explicitly [e.g. getIContextByName("ContextDB")] or with a simpler method that just returns whatever has been configured by some other mechanism - i.e. a suite of methods something like this:
getPossibleIContextImplementationNames()
setCurrentIContextImplementation({name})
getCurrentIContext()
Just as an aside, are you stuck with that naming? Because having a Context object that uses an IContext seems a little unusual. If your IContext implementations are actually used to retrieve data from somewhere, why not call the interface IDAO or IDataAccessor?

Can I stop C++/CLI from adding IDisposable to my ref class?

C++/CLI helpfully generates the IDisposable scaffolding for you when you implement a destructor on a ref class. Also, if you don't implement a destructor, but your class has a member variable which implements IDisposable, then IDisposable is again automatically implemented on your class. It's pretty helpful and much better than how IDisposable is handled in C#.
I have run into this behaviour when implementing a ref class that holds onto an msclr::com::ptr (a smart pointer that contains an RCW).
ref class Test /* : IDisposable added by the compiler */
{
msclr::com::ptr<IWhatever> _aComObject;
}
In my specific case, the COM object referenced by my class doesn't 'lock' some unmanaged resource, it effectively just uses up a bit of unmanaged memory that the CLR can't see. Therefore I would like to avoid confusing the users of my ref class by not implementing IDisposable the class. Instead I want to make the CLR aware of the existence of the COM object by using the GC API to add the appropriate memory pressure.
So, the question is: is there a way to suppress implementation of IDisposable on a ref class that doesn't implement a destructor, but does hold an IDisposable member variable?
NB: often this would be the wrong thing to do, as it would prevent users of the class from deterministically disposing of the underlying COM object, but given the particular circumstances, exposing IDisposable has the potential to confuse users of my ref class, since it really is not necessary to Dispose of the ref class in question.
I suppose one option would be to implement a variant of msclr::com::ptr without a destructor.
Any other method to suppress the automatic addition of IDisposable would be appreciated. Thanks.
Answer
Declare _aComObject as a handle to an msclr::com::ptr (msclr::com::ptr<IWhatever>^). The compiler does not then regard Test as being the 'owner' of the com ptr object, and does not Dispose it when Test is deleted.
I think the answer is to hold a handle to the msclr::com::ptr rather than holding it 'by value' (which is still holding it as a handle 'behind the scenes', except the C++CLI compiler treats it as a value - 'deleting' it (calling Dispose) when the owner object is deleted (Disposed)).
I'm not sure I agree with the ratioanle for avoiding the IDispose implementation -- but why not just store an IWhatever* in your class. The compiler shouldn't then generate the IDisposable implementation.
If you don't want the destructor behaviour then what benefit is the com::ptr wrapper buying you? You can always declare an com::ptr on the stack and assign your member pointer to it in any given method if you really need it.