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:com.github.drinkjava2.jbeanbox.springsrc.ReflectionUtils.java

/**
 * Given the source object and the destination, which must be the same class or a subclass, copy all fields,
 * including inherited fields. Designed to work on objects with public no-arg constructors.
 *//*from   ww w.j  a  v a2  s  .c o m*/
public static void shallowCopyFieldState(final Object src, final Object dest) {
    if (src == null) {
        throw new IllegalArgumentException("Source for field copy cannot be null");
    }
    if (dest == null) {
        throw new IllegalArgumentException("Destination for field copy cannot be null");
    }
    if (!src.getClass().isAssignableFrom(dest.getClass())) {
        throw new IllegalArgumentException("Destination class [" + dest.getClass().getName()
                + "] must be same or subclass as source class [" + src.getClass().getName() + "]");
    }
    doWithFields(src.getClass(), new FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            makeAccessible(field);
            Object srcValue = field.get(src);
            field.set(dest, srcValue);
        }
    }, COPYABLE_FIELDS);
}

From source file:com.cloud.api.ApiDispatcher.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static void setFieldValue(Field field, BaseCmd cmdObj, Object paramObj, Parameter annotation)
        throws IllegalArgumentException, ParseException {
    try {//from  w w w  .  j a v  a  2 s.  c  o  m
        field.setAccessible(true);
        CommandType fieldType = annotation.type();
        switch (fieldType) {
        case BOOLEAN:
            field.set(cmdObj, Boolean.valueOf(paramObj.toString()));
            break;
        case DATE:
            // This piece of code is for maintaining backward compatibility
            // and support both the date formats(Bug 9724)
            // Do the date messaging for ListEventsCmd only
            if (cmdObj instanceof ListEventsCmd) {
                boolean isObjInNewDateFormat = isObjInNewDateFormat(paramObj.toString());
                if (isObjInNewDateFormat) {
                    DateFormat newFormat = BaseCmd.NEW_INPUT_FORMAT;
                    synchronized (newFormat) {
                        field.set(cmdObj, newFormat.parse(paramObj.toString()));
                    }
                } else {
                    DateFormat format = BaseCmd.INPUT_FORMAT;
                    synchronized (format) {
                        Date date = format.parse(paramObj.toString());
                        if (field.getName().equals("startDate")) {
                            date = messageDate(date, 0, 0, 0);
                        } else if (field.getName().equals("endDate")) {
                            date = messageDate(date, 23, 59, 59);
                        }
                        field.set(cmdObj, date);
                    }
                }
            } else {
                DateFormat format = BaseCmd.INPUT_FORMAT;
                format.setLenient(false);
                synchronized (format) {
                    field.set(cmdObj, format.parse(paramObj.toString()));
                }
            }
            break;
        case FLOAT:
            // Assuming that the parameters have been checked for required before now,
            // we ignore blank or null values and defer to the command to set a default
            // value for optional parameters ...
            if (paramObj != null && isNotBlank(paramObj.toString())) {
                field.set(cmdObj, Float.valueOf(paramObj.toString()));
            }
            break;
        case INTEGER:
            // Assuming that the parameters have been checked for required before now,
            // we ignore blank or null values and defer to the command to set a default
            // value for optional parameters ...
            if (paramObj != null && isNotBlank(paramObj.toString())) {
                field.set(cmdObj, Integer.valueOf(paramObj.toString()));
            }
            break;
        case LIST:
            List listParam = new ArrayList();
            StringTokenizer st = new StringTokenizer(paramObj.toString(), ",");
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                CommandType listType = annotation.collectionType();
                switch (listType) {
                case INTEGER:
                    listParam.add(Integer.valueOf(token));
                    break;
                case UUID:
                    if (token.isEmpty())
                        break;
                    Long internalId = translateUuidToInternalId(token, annotation);
                    listParam.add(internalId);
                    break;
                case LONG: {
                    listParam.add(Long.valueOf(token));
                }
                    break;
                case SHORT:
                    listParam.add(Short.valueOf(token));
                case STRING:
                    listParam.add(token);
                    break;
                }
            }
            field.set(cmdObj, listParam);
            break;
        case UUID:
            if (paramObj.toString().isEmpty())
                break;
            Long internalId = translateUuidToInternalId(paramObj.toString(), annotation);
            field.set(cmdObj, internalId);
            break;
        case LONG:
            field.set(cmdObj, Long.valueOf(paramObj.toString()));
            break;
        case SHORT:
            field.set(cmdObj, Short.valueOf(paramObj.toString()));
            break;
        case STRING:
            if ((paramObj != null) && paramObj.toString().length() > annotation.length()) {
                s_logger.error("Value greater than max allowed length " + annotation.length() + " for param: "
                        + field.getName());
                throw new InvalidParameterValueException("Value greater than max allowed length "
                        + annotation.length() + " for param: " + field.getName());
            }
            field.set(cmdObj, paramObj.toString());
            break;
        case TZDATE:
            field.set(cmdObj, DateUtil.parseTZDateString(paramObj.toString()));
            break;
        case MAP:
        default:
            field.set(cmdObj, paramObj);
            break;
        }
    } catch (IllegalAccessException ex) {
        s_logger.error("Error initializing command " + cmdObj.getCommandName() + ", field " + field.getName()
                + " is not accessible.");
        throw new CloudRuntimeException("Internal error initializing parameters for command "
                + cmdObj.getCommandName() + " [field " + field.getName() + " is not accessible]");
    }
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

/**
 * Setup SSL connection./*from  ww w .ja  v a 2s. c o  m*/
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    final SSLContext sslContext;
    try {
        // SSL certificates are provided by the Guardian Project:
        // https://github.com/guardianproject/cacert
        if (trustManagers == null) {
            // 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);
            trustManagers = 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, trustManagers, 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:net.ostis.sc.memory.SCKeynodesBase.java

protected static void init(SCSession session, Class<? extends SCKeynodesBase> klass) {
    if (log.isDebugEnabled())
        log.debug("Start retrieving keynodes for " + klass);

    try {/*from w  w w.ja  v a 2 s  .c  om*/
        //
        // Search default segment for keynodes
        //
        SCSegment defaultSegment = null;
        {
            DefaultSegment annotation = klass.getAnnotation(DefaultSegment.class);
            if (annotation != null) {
                defaultSegment = session.openSegment(annotation.value());
                Validate.notNull(defaultSegment, "Default segment \"{0}\" not found", annotation.value());
                klass.getField(annotation.fieldName()).set(null, defaultSegment);
            }
        }

        Field[] fields = klass.getFields();
        for (Field field : fields) {
            int modifiers = field.getModifiers();

            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
                Class<?> type = field.getType();
                if (type.equals(SCSegment.class)) {
                    //
                    // We have segment field. Load segment by uri.
                    //
                    SegmentURI annotation = field.getAnnotation(SegmentURI.class);

                    if (annotation != null) {
                        String uri = annotation.value();
                        SCSegment segment = session.openSegment(uri);
                        field.set(null, segment);
                    } else {
                        // May be it already has value?
                        if (log.isWarnEnabled()) {
                            if (field.get(null) == null)
                                log.warn(field + " doesn't have value");
                        }
                    }
                } else {
                    if (!(checkKeynode(session, defaultSegment, field) || checkKeynodeURI(session, field)
                            || checkKeynodesNumberPatternURI(session, klass, field))) {

                        if (log.isWarnEnabled()) {
                            if (field.get(null) == null)
                                log.warn(field + " doesn't have annotations and value");
                        }

                    }
                }
            }
        }
    } catch (Exception e) {
        // TODO: handle
        e.printStackTrace();
    }
}

From source file:be.fedict.eid.applet.service.AppletServiceServlet.java

public static void injectInitParams(ServletConfig config, MessageHandler<?> messageHandler)
        throws ServletException, IllegalArgumentException, IllegalAccessException {
    Class<?> messageHandlerClass = messageHandler.getClass();
    Field[] fields = messageHandlerClass.getDeclaredFields();
    for (Field field : fields) {
        InitParam initParamAnnotation = field.getAnnotation(InitParam.class);
        if (null == initParamAnnotation) {
            continue;
        }/*  ww  w  . ja  v  a2 s  .c o  m*/
        String initParamName = initParamAnnotation.value();
        Class<?> fieldType = field.getType();
        field.setAccessible(true);
        if (ServiceLocator.class.equals(fieldType)) {
            /*
             * We always inject a service locator.
             */
            ServiceLocator<Object> fieldValue = new ServiceLocator<Object>(initParamName, config);
            field.set(messageHandler, fieldValue);
            continue;
        }
        String initParamValue = config.getInitParameter(initParamName);
        if (initParamAnnotation.required() && null == initParamValue) {
            throw new ServletException("missing required init-param: " + initParamName + " for message handler:"
                    + messageHandlerClass.getName());
        }
        if (null == initParamValue) {
            continue;
        }
        if (Boolean.TYPE.equals(fieldType)) {
            LOG.debug("injecting boolean: " + initParamValue);
            Boolean fieldValue = Boolean.parseBoolean(initParamValue);
            field.set(messageHandler, fieldValue);
            continue;
        }
        if (String.class.equals(fieldType)) {
            field.set(messageHandler, initParamValue);
            continue;
        }
        if (InetAddress.class.equals(fieldType)) {
            InetAddress inetAddress;
            try {
                inetAddress = InetAddress.getByName(initParamValue);
            } catch (UnknownHostException e) {
                throw new ServletException("unknown host: " + initParamValue);
            }
            field.set(messageHandler, inetAddress);
            continue;
        }
        if (Long.class.equals(fieldType)) {
            Long fieldValue = Long.parseLong(initParamValue);
            field.set(messageHandler, fieldValue);
            continue;
        }
        throw new ServletException("unsupported init-param field type: " + fieldType.getName());
    }
}

From source file:framework.GlobalHelpers.java

private static Object createController(Class<?> clazz) throws InstantiationException, IllegalAccessException {
    Object controller = clazz.newInstance();
    // IoC by name
    // TODO what about IoC by type?
    Field field = findInheritedField(controller.getClass(), "app");
    if (field != null) {
        field.setAccessible(true);//  w  ww  .ja v  a  2s  .co m
        field.set(controller, FrameworkServlet.application);
    }
    controllersCache.put(clazz, controller);
    return controller;
}

From source file:forge.quest.io.QuestDataIO.java

private static <T> void setFinalField(final Class<T> clasz, final String fieldName, final T instance,
        final Object newValue) throws IllegalAccessException, NoSuchFieldException {
    final Field field = clasz.getDeclaredField(fieldName);
    field.setAccessible(true);/*ww  w  . j  a  va  2  s  .  c o  m*/
    field.set(instance, newValue); // no difference here (used only to set
                                   // initial lives)
}

From source file:org.cybercat.automation.annotations.AnnotationBuilder.java

@SuppressWarnings("unchecked")
private static final void createIntegrationService(Field field, Object targetObject)
        throws AutomationFrameworkException {
    Class<IIntegrationService> clazz;
    try {/*from   ww w . j av  a2s . co m*/
        clazz = (Class<IIntegrationService>) field.getType();
    } catch (Exception e) {
        throw new AutomationFrameworkException("Unexpected field type :" + field.getType().getSimpleName()
                + " field name: " + field.getName() + " class: " + targetObject.getClass().getSimpleName()
                + " Thread ID:" + Thread.currentThread().getId()
                + " \n\tThis field must be of the type that extends AbstractPageObject class.", e);
    }
    try {

        field.set(targetObject,
                createIntegrationService(clazz, field.getAnnotation(CCIntegrationService.class)));
    } catch (Exception e) {
        throw new AutomationFrameworkException(
                "Set filed exception. Please, save this log and contact the Cybercat project support."
                        + " field name: " + field.getName() + " class: "
                        + targetObject.getClass().getSimpleName() + " Thread ID:"
                        + Thread.currentThread().getId(),
                e);
    }

}

From source file:org.chorusbdd.chorus.spring.SpringContextInjector.java

private static void injectResourceFields(ApplicationContext springContext, Object handler, Class handlerClass) {
    ChorusLog log = ChorusLogFactory.getLog(SpringContextInjector.class);

    //inject handler fields with the Spring beans
    Field[] fields = handlerClass.getDeclaredFields();
    for (Field field : fields) {
        Resource resourceAnnotation = field.getAnnotation(Resource.class);
        if (resourceAnnotation != null) {
            boolean beanNameInAnnotation = !"".equals(resourceAnnotation.name());
            String name = beanNameInAnnotation ? resourceAnnotation.name() : field.getName();
            Object bean = springContext.getBean(name);
            log.trace("Found spring Resource annotation for field " + field
                    + " will attempt to inject Spring bean " + bean);
            if (bean == null) {
                log.error(//from ww  w  .java2s . c o  m
                        "Failed to set @Resource (" + name + "). No such bean exists in application context.");
            }
            try {
                field.setAccessible(true);
                field.set(handler, bean);
            } catch (IllegalAccessException e) {
                log.error("Failed to set @Resource (" + name + ") with bean of type: " + bean.getClass(), e);
            }
        }
    }

    Class superclass = handlerClass.getSuperclass();
    if (superclass != Object.class) {
        injectResourceFields(springContext, handler, superclass);
    }
}

From source file:com.diversityarrays.kdxplore.importdata.bms.BmsExcelImportHelper.java

static private void storeValueInEntity(Class<? extends KDSmartDbEntity> cls, KDSmartDbEntity entity,
        Field field, String cell_value) throws IOException {
    try {//  w w  w  . j  a  v  a2s  .co  m
        Object valueToStore = ImportAsHeading.checkAndConvertValue(null, cls, field, cell_value);
        field.set(entity, valueToStore);
    } catch (InvalidValueException e) {
        throw new IOException(e);
    } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new IOException(e);
    }
}