View Javadoc
1   /*******************************************************************************
2    * Portions created by Sebastian Thomschke are copyright (c) 2005-2015 Sebastian
3    * Thomschke.
4    *
5    * All Rights Reserved. This program and the accompanying materials
6    * are made available under the terms of the Eclipse Public License v1.0
7    * which accompanies this distribution, and is available at
8    * http://www.eclipse.org/legal/epl-v10.html
9    *
10   * Contributors:
11   *     Sebastian Thomschke - initial implementation.
12   *******************************************************************************/
13  package net.sf.oval.internal.util;
14  
15  import java.io.IOException;
16  import java.io.Serializable;
17  import java.lang.reflect.Field;
18  import java.util.WeakHashMap;
19  
20  import net.sf.oval.internal.Log;
21  
22  /**
23   * Serializable Wrapper for java.lang.reflect.Field objects since they do not implement Serializable
24   *
25   * @author Sebastian Thomschke
26   */
27  public final class SerializableField implements Serializable
28  {
29  	private static final Log LOG = Log.getLog(SerializableField.class);
30  
31  	private static final WeakHashMap<Field, SerializableField> CACHE = new WeakHashMap<Field, SerializableField>();
32  
33  	private static final long serialVersionUID = 1L;
34  
35  	public static SerializableField getInstance(final Field field)
36  	{
37  		synchronized (CACHE)
38  		{
39  			SerializableField sm = CACHE.get(field);
40  			if (sm == null)
41  			{
42  				sm = new SerializableField(field);
43  				CACHE.put(field, sm);
44  			}
45  			return sm;
46  		}
47  	}
48  
49  	private final Class< ? > declaringClass;
50  	private transient Field field;
51  	private final String name;
52  
53  	private SerializableField(final Field field)
54  	{
55  		this.field = field;
56  		name = field.getName();
57  		declaringClass = field.getDeclaringClass();
58  	}
59  
60  	/**
61  	 * @return the declaringClass
62  	 */
63  	public Class< ? > getDeclaringClass()
64  	{
65  		return declaringClass;
66  	}
67  
68  	/**
69  	 * @return the field
70  	 */
71  	public Field getField()
72  	{
73  		return field;
74  	}
75  
76  	/**
77  	 * @return the name
78  	 */
79  	public String getName()
80  	{
81  		return name;
82  	}
83  
84  	private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
85  	{
86  		in.defaultReadObject();
87  		try
88  		{
89  			field = declaringClass.getDeclaredField(name);
90  		}
91  		catch (final NoSuchFieldException ex)
92  		{
93  			LOG.debug("Unexpected NoSuchFieldException occured", ex);
94  			throw new IOException(ex.getMessage());
95  		}
96  	}
97  }