I have an object that is either type of int, short, byte or long and I need to give it a new value. Would that be possible in Java ? And if yes how ?
public static void set(Object obj, int value) throws Exception
{
Class<?> c = obj.getClass();
if (c.equals(Integer.class))
{
// ???
}
}
Integer is immutable. You cannot set a value to an Integer
instance.
Similarly, other wrapper classes for primitive types are also immutable.
Yes, so long as you know what primitive type you're dealing with.
Class clazz = Class.forName("TheClass");
Field f = clazz.getDeclaredField("ThePrimitiveField");
Object obj;
f.setBoolean(obj, true);
This will change the "ThePrimitiveField" field of obj. If you don't know the type...
Field f;
Object obj;
try {
f.setBoolean(obj, true);
} catch (IllegalArgumentException ex) {
try {
f.setByte(obj, 16);
} catch (IllegalArgumentException ex) {
try {
f.setChar(obj, 'a');
// etc
}
}
}
If you know the type do this:
public class Main
{
public static void main(String[] args)
throws NoSuchFieldException,
IllegalArgumentException,
IllegalAccessException
{
Foo fooA;
Foo fooB;
final Class<?> clazz;
final Field field;
fooA = new Foo();
fooB = new Foo();
clazz = fooA.getClass();
field = clazz.getDeclaredField("bar");
System.out.println(fooA.getBar());
System.out.println(fooB.getBar());
field.setAccessible(true); // have to do this since bar is private
field.set(fooA, 42);
System.out.println(fooA.getBar());
System.out.println(fooB.getBar());
}
}
class Foo
{
private int bar;
public int getBar()
{
return (bar);
}
}
If you do not know the type you can do something like this:
public class Main
{
public static void main(String[] args)
throws NoSuchFieldException,
IllegalArgumentException,
IllegalAccessException
{
Foo fooA;
Foo fooB;
final Class<?> clazz;
final Class<?> type;
final Field field;
fooA = new Foo();
fooB = new Foo();
clazz = fooA.getClass();
field = clazz.getDeclaredField("bar");
System.out.println(fooA.getBar());
System.out.println(fooB.getBar());
field.setAccessible(true); // have to do this since bar is private
type = field.getType();
if(type.equals(int.class))
{
field.set(fooA, 42);
}
else if(type.equals(byte.class))
{
field.set(fooA, (byte)1);
}
else if(type.equals(char.class))
{
field.set(fooA, 'A');
}
System.out.println(fooA.getBar());
System.out.println(fooB.getBar());
}
}
class Foo
{
private char bar;
public char getBar()
{
return (bar);
}
}
And, if you want to use wrapper classes (Integer, Character, etc..) you can add this:
else if(type.equals(Integer.class))
{
field.set(fooA, new Integer(43));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.