View Javadoc

1   /*
2    * Copyright 2005,2009 Ivan SZKIBA
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.ini4j;
17  
18  import org.ini4j.spi.AbstractBeanInvocationHandler;
19  
20  import java.lang.reflect.Proxy;
21  
22  import java.util.prefs.Preferences;
23  
24  public final class PreferencesBean
25  {
26      private PreferencesBean()
27      {
28      }
29  
30      public static <T> T newInstance(Class<T> clazz, final Preferences prefs)
31      {
32          return clazz.cast(Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new Handler(prefs)));
33      }
34  
35      private static class Handler extends AbstractBeanInvocationHandler
36      {
37          private final Preferences _prefs;
38  
39          public Handler(Preferences prefs)
40          {
41              _prefs = prefs;
42          }
43  
44          @Override protected Object getPropertySpi(String property, Class<?> clazz)
45          {
46              return _prefs.get(property, null);
47          }
48  
49          @Override protected void setPropertySpi(String property, Object value, Class<?> clazz)
50          {
51              _prefs.put(property, value.toString());
52          }
53  
54          @Override protected boolean hasPropertySpi(String property)
55          {
56              return _prefs.get(property, null) != null;
57          }
58      }
59  }