1 /** 2 * Copyright 2006-2017 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 */ 16 package org.objenesis.instantiator.gcj; 17 18 import java.io.IOException; 19 import java.io.ObjectInputStream; 20 import java.lang.reflect.Method; 21 22 import org.objenesis.ObjenesisException; 23 import org.objenesis.instantiator.ObjectInstantiator; 24 25 /** 26 * Base class for GCJ-based instantiators. It initializes reflection access to method 27 * ObjectInputStream.newObject, as well as creating a dummy ObjectInputStream to be used as the 28 * "this" argument for the method. 29 * 30 * @author Leonardo Mesquita 31 */ 32 public abstract class GCJInstantiatorBase<T> implements ObjectInstantiator<T> { 33 static Method newObjectMethod = null; 34 static ObjectInputStream dummyStream; 35 36 private static class DummyStream extends ObjectInputStream { 37 public DummyStream() throws IOException { 38 } 39 } 40 41 private static void initialize() { 42 if(newObjectMethod == null) { 43 try { 44 newObjectMethod = ObjectInputStream.class.getDeclaredMethod("newObject", new Class[] { 45 Class.class, Class.class}); 46 newObjectMethod.setAccessible(true); 47 dummyStream = new DummyStream(); 48 } 49 catch(RuntimeException e) { 50 throw new ObjenesisException(e); 51 } 52 catch(NoSuchMethodException e) { 53 throw new ObjenesisException(e); 54 } 55 catch(IOException e) { 56 throw new ObjenesisException(e); 57 } 58 } 59 } 60 61 protected final Class<T> type; 62 63 public GCJInstantiatorBase(Class<T> type) { 64 this.type = type; 65 initialize(); 66 } 67 68 public abstract T newInstance(); 69 } 70