Home > Back-end >  Setting RenderingHints from a String value
Setting RenderingHints from a String value

Time:10-22

I'm trying to populate some RenderingHints from a value that will be set using a String (e.g. from a value in the application.properties file), but cannot get it to pass through the value when setting the field dynamically.

Is there any easy way I can achieve this? I guess I'm either missing a Cast statement, or just not understanding how reflection works. Thanks.

import java.awt.RenderingHints;
import java.lang.reflect.Field;

...

// create the string we want to populate the hint from
String myHint = "VALUE_ANTIALIAS_ON";


// create the new hints that we want to populate
RenderingHints renderingHints = new RenderingHints(null);


// setting the value directly (like this) works:
renderingHints.put(RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);


// but using reflection to retrieve the field:
Field hintField = RenderingHints.class.getField(myHint);


// doesn't work...
renderingHints.put(RenderingHints.KEY_ANTIALIASING, hintField);


// and gives the error:
// public static final java.lang.Object java.awt.RenderingHints.VALUE_ANTIALIAS_ON incompatible with Global antialiasing enable key

CodePudding user response:

It doesn’t work because an instance of java.lang.reflect.Field isn’t an instance of java.awt.RenderingHints. You need to get the value of the field:

final Object hint = hintField.get(null);
renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);
  • Related