Example usage for java.lang.reflect Field set

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the field represented by this Field object on the specified object argument to the specified new value.

Usage

From source file:Main.java

/**
 * Replace the value of a field containing a non null array, by a new array containing the elements of the original
 * array plus the elements of extraElements.
 *
 * @param instance the instance whose field is to be modified.
 * @param fieldName the field to modify.
 * @param extraElements elements to append at the end of the array.
 *//* w  w w .  j a v a2  s .c  o m*/
static void expandFieldArray(Object instance, String fieldName, Object[] extraElements)
        throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    Field jlrField = findField(instance, fieldName);
    Object[] original = (Object[]) jlrField.get(instance);
    Object[] combined = (Object[]) Array.newInstance(original.getClass().getComponentType(),
            original.length + extraElements.length);
    System.arraycopy(extraElements, 0, combined, 0, extraElements.length);
    System.arraycopy(original, 0, combined, extraElements.length, original.length);
    jlrField.set(instance, combined);
}

From source file:io.github.sparta.helpers.reflex.Reflections.java

/** , private/protected, ??setter. */
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
        throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
    }//  w  ww .  j av  a2s  .c  o m

    try {
        field.set(obj, value);
    } catch (IllegalAccessException e) {
        log.error("??!", e);
    }
}

From source file:Main.java

/**
 * Set property(field) of the specified object.
 * @param bean The object which has the given property
 * @param field The field to be set/*from  w ww .j av a 2  s.co  m*/
 * @param value The value to be set to the field
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
public static void setProperty(Object bean, Field field, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (bean == null || field == null) {
        return;
    }

    try {
        field.setAccessible(true);
        field.set(bean, value);
    } catch (Exception e) {
    }

}

From source file:fr.paris.lutece.util.bean.BeanUtil.java

/**
 * Populate a bean using parameters in http request
 * /*from  ww w. j  av  a  2  s.  c  o m*/
 * @param bean bean to populate
 * @param request http request
 */
public static void populate(Object bean, HttpServletRequest request) {
    for (Field field : bean.getClass().getDeclaredFields()) {
        try {
            // for all boolean field, init to false
            if (field.getType().getName().equals(Boolean.class.getName())
                    || field.getType().getName().equals(boolean.class.getName())) {
                field.setAccessible(true);
                field.set(bean, false);
            }
        } catch (Exception e) {
            String error = "La valeur du champ " + field.getName() + " de la classe "
                    + bean.getClass().getName() + " n'a pas pu tre rcupr ";
            AppLogService.error(error);
            throw new RuntimeException(error, e);
        }
    }

    try {
        BeanUtils.populate(bean, convertMap(request.getParameterMap()));
    } catch (IllegalAccessException e) {
        AppLogService.error("Unable to fetch data from request", e);
    } catch (InvocationTargetException e) {
        AppLogService.error("Unable to fetch data from request", e);
    }
}

From source file:net.ljcomputing.gson.converter.impl.GsonConverterServiceImpl.java

/**
 * Sets the field values.//from w w w  .  jav a2s  . c om
 *
 * @param to the to
 * @param fieldTo the field to
 * @param from the from
 * @param fieldFrom the field from
 * @throws IllegalArgumentException the illegal argument exception
 * @throws IllegalAccessException the illegal access exception
 */
private static void setFieldValues(final Object to, final Field fieldTo, final Object from,
        final Field fieldFrom) throws IllegalArgumentException, IllegalAccessException {
    if (null != fieldTo && null != fieldFrom) {
        fieldTo.setAccessible(true);
        fieldFrom.setAccessible(true);
        fieldTo.set(to, fieldFrom.get(from));
    }
}

From source file:com.framework.infrastructure.utils.ReflectionUtils.java

/**
 * , private/protected, setter./*from   w  w  w  .j a  va 2 s  .co m*/
 */
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
        throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
    }

    try {
        field.set(obj, value);
    } catch (IllegalAccessException e) {
        logger.error(":{}", e.getMessage());
    }
}

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

/**
 * CommandLine parse und fehlende Argumente verlangen
 * @param args Args// ww  w .  ja va 2 s.c  o  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:com.cn.util.Reflections.java

/**
 * , private/protected, ??setter./*from www .jav a 2 s  .  co m*/
 */
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
        throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
    }

    try {
        field.set(obj, value);
    } catch (IllegalAccessException e) {
    }
}

From source file:com.eurelis.opencms.workflows.moduleconfiguration.ModuleConfigurationLoader.java

/**
 * Load the config file, extract value//from   w  ww.j  a  v  a  2  s. co  m
 * 
 * @param instance
 *            the instance to update
 * @throws IOException
 *             if a problem occurs during initialization
 */
private static void loadConfigFile(ModuleConfiguration instance) throws IOException {
    CmsResource resource = OpenCmsEasyAccess.getResource(CONFIG_FILE);

    if (resource != null) {
        if (resource.isFile()) {
            // Read the file
            byte[] fileContent = OpenCmsEasyAccess.readFile(resource);

            if (fileContent.length > 0) {

                // get a reader on the file
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(new ByteArrayInputStream(fileContent)));

                /*
                 * Read all lines of the files
                 */
                String readLine = null;
                while ((readLine = reader.readLine()) != null) {

                    //remove useless space and other
                    readLine = readLine.trim();

                    // ignore line starting with "#" or emptyline
                    if (!readLine.startsWith(COMMENT_STRING) && !readLine.equals("")) {

                        String[] configValues = readLine.split(SEPARATOR_STRING);
                        if (configValues.length > 1) {
                            Class moduleConfigurationClass = instance.getClass();
                            if (moduleConfigurationClass != null) {
                                try {
                                    //set the new value
                                    Field fieldToFill = moduleConfigurationClass
                                            .getField(configValues[0].trim());
                                    if (fieldToFill != null) {
                                        try {
                                            fieldToFill.set(instance, configValues[1].trim());
                                        } catch (IllegalArgumentException e) {
                                            LOGGER.info(ErrorFormatter.formatException(e));
                                        } catch (IllegalAccessException e) {
                                            LOGGER.info(ErrorFormatter.formatException(e));
                                        }
                                    } else {
                                        LOGGER.debug("No field associated to " + configValues[0]
                                                + " has been found");
                                    }

                                } catch (SecurityException e) {
                                    LOGGER.info(ErrorFormatter.formatException(e));
                                } catch (NoSuchFieldException e) {
                                    LOGGER.info(ErrorFormatter.formatException(e));
                                }
                            } else {
                                LOGGER.debug("The class of ModuleConfiguration instance has not been found !");
                            }
                        } else {
                            LOGGER.info("The line " + readLine + " doesn't correspond to a valid property");
                        }

                    }
                }

            } else {
                LOGGER.warn("The config file " + CONFIG_FILE + " is empty.");
            }
        } else {
            LOGGER.warn("The config file " + CONFIG_FILE + " is not a file.");
        }

    } else {
        LOGGER.warn("The config file " + CONFIG_FILE + " has not been found.");
    }

    //LOGGER.debug("WF | instance = "+instance);
}

From source file:Main.java

public static void cleanThreadLocals(Thread thread)
        throws NoSuchFieldException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException {
    if (thread == null)
        return;// w ww.ja v a  2 s .c  o m
    Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
    threadLocalsField.setAccessible(true);

    Class<?> threadLocalMapKlazz = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
    Field tableField = threadLocalMapKlazz.getDeclaredField("table");
    tableField.setAccessible(true);

    Object fieldLocal = threadLocalsField.get(thread);
    if (fieldLocal == null) {
        return;
    }
    Object table = tableField.get(fieldLocal);

    int threadLocalCount = Array.getLength(table);

    for (int i = 0; i < threadLocalCount; i++) {
        Object entry = Array.get(table, i);
        if (entry != null) {
            Field valueField = entry.getClass().getDeclaredField("value");
            valueField.setAccessible(true);
            Object value = valueField.get(entry);
            if (value != null) {

                if ("java.util.concurrent.ConcurrentLinkedQueue".equals(value.getClass().getName())
                        || "java.util.concurrent.ConcurrentHashMap".equals(value.getClass().getName())) {
                    valueField.set(entry, null);
                }
            }

        }
    }
}