1/**
2 * Copyright 2006-2013 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.objenesis.instantiator.sun;
17
18import java.io.NotSerializableException;
19import java.lang.reflect.Constructor;
20
21import org.objenesis.ObjenesisException;
22import org.objenesis.instantiator.ObjectInstantiator;
23import org.objenesis.instantiator.SerializationInstantiatorHelper;
24
25/**
26 * Instantiates an object using internal sun.reflect.ReflectionFactory - a class only available on
27 * JDK's that use Sun's 1.4 (or later) Java implementation. This instantiator will create classes in
28 * a way compatible with serialization, calling the first non-serializable superclass' no-arg
29 * constructor. This is the best way to instantiate an object without any side effects caused by the
30 * constructor - however it is not available on every platform.
31 *
32 * @author Leonardo Mesquita
33 * @see ObjectInstantiator
34 */
35public class SunReflectionFactorySerializationInstantiator implements ObjectInstantiator {
36
37   private final Constructor mungedConstructor;
38
39   public SunReflectionFactorySerializationInstantiator(Class type) {
40	  Class nonSerializableAncestor = SerializationInstantiatorHelper.getNonSerializableSuperClass(type);
41
42      Constructor nonSerializableAncestorConstructor;
43      try {
44         nonSerializableAncestorConstructor = nonSerializableAncestor
45            .getConstructor((Class[]) null);
46      }
47      catch(NoSuchMethodException e) {
48         throw new ObjenesisException(new NotSerializableException(type+" has no suitable superclass constructor"));
49      }
50
51      mungedConstructor = SunReflectionFactoryHelper.newConstructorForSerialization(
52         type, nonSerializableAncestorConstructor);
53      mungedConstructor.setAccessible(true);
54   }
55
56   public Object newInstance() {
57      try {
58         return mungedConstructor.newInstance((Object[]) null);
59      }
60      catch(Exception e) {
61         throw new ObjenesisException(e);
62      }
63   }
64}
65