Here you can find the source of setField(Class clazz, String name, Object value)
Parameter | Description |
---|---|
clazz | The class. |
name | The name of the field. |
value | The new value of the field. |
public static void setField(Class clazz, String name, Object value)
//package com.java2s; /*// w w w . java 2 s . co m * Copyright 2017, Leanplum, Inc. All rights reserved. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.lang.reflect.Field; public class Main { /** * Assigns a value to a field of a given class. * * @param clazz The class. * @param name The name of the field. * @param value The new value of the field. */ public static void setField(Class clazz, String name, Object value) { setField(clazz, null, name, value); } /** * Assigns a value to a field of a given object. * * @param object The object. * @param name The name of the field. * @param value The new value of the field. */ @SuppressWarnings("unused") public static void setField(Object object, String name, Object value) { setField(null, object, name, value); } /** * Assigns a value to a field of a given class or object. * * @param clazz The class. * @param object The object. * @param name The name of the field. * @param value The new value of the field. */ public static void setField(Class clazz, Object object, String name, Object value) { if (clazz == null && object == null) { return; } if (clazz == null) { clazz = object.getClass(); } try { Field field = clazz.getDeclaredField(name); try { field.setAccessible(true); field.set(object, value); } catch (IllegalAccessException e) { e.printStackTrace(); } } catch (NoSuchFieldException e) { e.printStackTrace(); } } }