Example usage for java.lang.reflect Field setAccessible

List of usage examples for java.lang.reflect Field setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Field setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:com.palantir.ptoss.util.Reflections.java

/**
 * Given an {@link Object} and a {@link Field} of a known {@link Class} type, get the field.
 * This will return the value of the field regardless of visibility modifiers (i.e., it will
 * return the value of private fields.)//  w ww  .  j a v  a  2 s. com
 */
public static <T> T getFieldObject(Object object, Field field, Class<T> klass) {
    try {
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        Object fieldObject = field.get(object);
        field.setAccessible(accessible);
        return klass.cast(fieldObject);
    } catch (IllegalAccessException e) {
        // shouldn't happen since we set accessibility above.
        return null;
    }
}

From source file:ch.admin.hermes.etl.load.HermesETLApplication.java

/**
 * CommandLine parse und fehlende Argumente verlangen
 * @param args Args/*from ww w  .  j  a  v  a 2 s  . co  m*/
 * @throws ParseException
 */
private static void parseCommandLine(String[] args) throws Exception {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

    // HACK um UTF-8 CharSet fuer alle Dateien zu setzen (http://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding)
    System.setProperty("file.encoding", "UTF-8");
    Field charset = Charset.class.getDeclaredField("defaultCharset");
    charset.setAccessible(true);
    charset.set(null, null);

    // commandline Options - FremdsystemSite, Username und Password
    Options options = new Options();
    options.addOption("s", true, "Zielsystem - URL");
    options.addOption("u", true, "Zielsystem - Username");
    options.addOption("p", true, "Zielsystem - Password");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    site = cmd.getOptionValue("s");
    user = cmd.getOptionValue("u");
    passwd = cmd.getOptionValue("p");

    // restliche Argumente pruefen - sonst usage ausgeben
    String[] others = cmd.getArgs();
    if (others.length >= 1 && (others[0].endsWith(".js") || others[0].endsWith(".ftl")))
        script = others[0];
    if (others.length >= 2 && others[1].endsWith(".xml"))
        model = others[1];

    // Dialog mit allen Werten zusammenstellen
    JComboBox<String> scenarios = new JComboBox<String>(crawler.getScenarios());

    JTextField tsite = new JTextField(45);
    tsite.setText(site);
    JTextField tuser = new JTextField(16);
    tuser.setText(user);
    JPasswordField tpasswd = new JPasswordField(16);
    tpasswd.setText(passwd);
    final JTextField tscript = new JTextField(45);
    tscript.setText(script);
    final JTextField tmodel = new JTextField(45);
    tmodel.setText(model);

    JPanel myPanel = new JPanel(new GridLayout(6, 2));
    myPanel.add(new JLabel("Szenario (von http://www.hermes.admin.ch):"));
    myPanel.add(scenarios);

    myPanel.add(new JLabel("XML Model:"));
    myPanel.add(tmodel);
    JPanel pmodel = new JPanel();
    pmodel.add(tmodel);
    JButton bmodel = new JButton("...");
    pmodel.add(bmodel);
    bmodel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            model = getFile("Szenario XML Model", new String[] { "XML Model" }, new String[] { ".xml" });
            if (model != null)
                tmodel.setText(model);
        }
    });
    myPanel.add(pmodel);

    scenarios.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            try {
                Object o = e.getItem();
                tmodel.setText(crawler.getModelURL(o.toString()));
                scenario = o.toString();
            } catch (Exception e1) {
            }
        }
    });

    // Script
    myPanel.add(new JLabel("Umwandlungs-Script:"));
    JPanel pscript = new JPanel();
    pscript.add(tscript);
    JButton bscript = new JButton("...");
    pscript.add(bscript);
    myPanel.add(pscript);
    bscript.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            script = getFile("JavaScript/Freemarker Umwandlungs-Script",
                    new String[] { "JavaScript", "Freemarker" }, new String[] { ".js", ".ftl" });
            if (script != null)
                tscript.setText(script);
        }
    });

    // Zielsystem Angaben
    myPanel.add(new JLabel("Zielsystem URL:"));
    myPanel.add(tsite);
    myPanel.add(new JLabel("Zielsystem Benutzer:"));
    myPanel.add(tuser);
    myPanel.add(new JLabel("Zielsystem Password:"));
    myPanel.add(tpasswd);

    // Trick um Feld scenario und model zu setzen.
    if (scenarios.getItemCount() >= 8)
        scenarios.setSelectedIndex(8);

    // Dialog
    int result = JOptionPane.showConfirmDialog(null, myPanel, "HERMES 5 XML Model nach Fremdsystem/Format",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        site = tsite.getText();
        user = tuser.getText();
        passwd = new String(tpasswd.getPassword());
        model = tmodel.getText();
        script = tscript.getText();
    } else
        System.exit(1);

    if (model == null || script == null || script.trim().length() == 0)
        usage();

    if (script.endsWith(".js"))
        if (site == null || user == null || passwd == null || user.trim().length() == 0
                || passwd.trim().length() == 0)
            usage();
}

From source file:net.drgnome.virtualpack.components.VAnvil.java

public static IInventory getInv(VAnvil anvil, String name) {
        try {//w  w w  .j  a  va2  s.  c  o m
            Field f = ContainerAnvil.class.getDeclaredField(name);
            f.setAccessible(true);
            return (IInventory) f.get(anvil);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

From source file:org.querybyexample.jpa.JpaUtil.java

public static Object getValueFromField(Field field, Object object) {
    boolean accessible = field.isAccessible();
    try {/*from ww  w. j av  a  2 s  .c  om*/
        return ReflectionUtils.getField(field, object);
    } finally {
        field.setAccessible(accessible);
    }
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Setup SSL connection./*from  w  w w  . j a va2 s . co m*/
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Load custom SSL certificates");
    }

    final SSLContext sslContext;
    try {
        // Load SSL certificates:
        // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
        // Earlier Android versions do not have updated root CA
        // certificates, resulting in connection errors.
        final KeyStore keyStore = loadCertificates(context);

        final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore);
        final TrustManager[] tms = new TrustManager[] { customTrustManager };

        // Init SSL connection with custom certificates.
        // The same SecureRandom instance is used for every connection to
        // speed up initialization.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tms, SECURE_RANDOM);
    } catch (GeneralSecurityException e) {
        final IOException ioe = new IOException("Failed to initialize SSL engine");
        ioe.initCause(e);
        throw ioe;
    }

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Fix slow read:
        // http://code.google.com/p/android/issues/detail?id=13117
        // Prior to ICS, the host name is still resolved even if we already
        // know its IP address, for each connection.
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        final SSLSocketFactory socketFactory = new SSLSocketFactory() {
            @Override
            public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
            }

            @Override
            public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
            }

            @Override
            public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
                    throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
            }

            @Override
            public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
                    throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
            }

            private void injectHostname(InetAddress address, String host) {
                try {
                    Field field = InetAddress.class.getDeclaredField("hostName");
                    field.setAccessible(true);
                    field.set(address, host);
                } catch (Exception ignored) {
                }
            }

            @Override
            public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
            }

            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }

            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
        };
        conn.setSSLSocketFactory(socketFactory);
    } else {
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}

From source file:edu.mayo.cts2.framework.model.util.ModelUtils.java

public static ChangeableResource createChangeableResource(IsChangeable changeable) {
    ChangeableResource choice = new ChangeableResource();

    for (Field field : choice.getClass().getDeclaredFields()) {
        if (field.getType().equals(changeable.getClass()) || field.getName().equals("_choiceValue")) {
            field.setAccessible(true);
            try {
                field.set(choice, changeable);
            } catch (IllegalArgumentException e) {
                throw new IllegalStateException(e);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException(e);
            }/*from  w w  w.jav  a 2 s  .  c om*/
        }
    }

    return choice;
}

From source file:net.minecraftforge.common.util.EnumHelper.java

public static void setFailsafeFieldValue(Field field, @Nullable Object target, @Nullable Object value)
        throws Exception {
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);/*from w w w.  j a  va  2s . c  o  m*/
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    Object fieldAccessor = newFieldAccessor.invoke(reflectionFactory, field, false);
    fieldAccessorSet.invoke(fieldAccessor, target, value);
}

From source file:Main.java

public static int hashCode(Object target) {
    if (target == null)
        return 0;
    final int prime = 31;
    int result = 1;

    Class<?> current = target.getClass();
    do {//w  ww.j  a v a  2s .c o m
        for (Field f : current.getDeclaredFields()) {
            if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())
                    || f.isSynthetic()) {
                continue;
            }

            Object self;
            try {
                f.setAccessible(true);
                self = f.get(target);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
            if (self == null) {
                result = prime * result + 0;
            } else if (self.getClass().isArray()) {
                if (self.getClass().equals(boolean[].class)) {
                    result = prime * result + Arrays.hashCode((boolean[]) self);
                } else if (self.getClass().equals(char[].class)) {
                    result = prime * result + Arrays.hashCode((char[]) self);
                } else if (self.getClass().equals(byte[].class)) {
                    result = prime * result + Arrays.hashCode((byte[]) self);
                } else if (self.getClass().equals(short[].class)) {
                    result = prime * result + Arrays.hashCode((short[]) self);
                } else if (self.getClass().equals(int[].class)) {
                    result = prime * result + Arrays.hashCode((int[]) self);
                } else if (self.getClass().equals(long[].class)) {
                    result = prime * result + Arrays.hashCode((long[]) self);
                } else if (self.getClass().equals(float[].class)) {
                    result = prime * result + Arrays.hashCode((float[]) self);
                } else if (self.getClass().equals(double[].class)) {
                    result = prime * result + Arrays.hashCode((double[]) self);
                } else {
                    result = prime * result + Arrays.hashCode((Object[]) self);
                }
            } else {
                result = prime * result + self.hashCode();
            }

            System.out.println(f.getName() + ": " + result);
        }
        current = current.getSuperclass();
    } while (!Object.class.equals(current));

    return result;
}

From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java

/**
 * @return the {@link Field} of given class with given name or <code>null</code> if no such {@link Field}
 *         found./*  w  w w .ja va2 s  . c o  m*/
 */
public static Field getFieldByName(Class<?> clazz, String name) {
    Assert.isNotNull(clazz);
    Assert.isNotNull(name);
    // check fields of given class and its super classes
    while (clazz != null) {
        // check all declared field
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().equals(name)) {
                field.setAccessible(true);
                return field;
            }
        }
        // check interfaces
        {
            Class<?>[] interfaceClasses = clazz.getInterfaces();
            for (Class<?> interfaceClass : interfaceClasses) {
                Field field = getFieldByName(interfaceClass, name);
                if (field != null) {
                    return field;
                }
            }
        }
        // check superclass
        clazz = clazz.getSuperclass();
    }
    // not found
    return null;
}

From source file:misc.TestUtils.java

public static List<Pair<String, Object>> getEntityFields(Object o) {
    List<Pair<String, Object>> ret = new ArrayList<Pair<String, Object>>();
    for (Class<?> clazz = o.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
        for (Field field : clazz.getDeclaredFields()) {
            //ignore some weird fields with unique values
            if (field.getName().contains("$"))
                continue;
            boolean accessible = field.isAccessible();
            try {
                field.setAccessible(true);
                Object val = field.get(o);
                ret.add(new Pair<String, Object>(field.getName(), val));
                //               System.out.println(field.getName()+"="+val);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();/* w  ww.java2  s  .  c  om*/
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } finally {
                field.setAccessible(accessible);
            }
        }
    }
    return ret;
}