下面列出了java.lang.reflect.Field#setBoolean ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Get the initial context.
*
* @param environment the environment.
* @return the initial context.
* @throws NamingException when a naming error occurs.
*/
@Override
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
try {
Field closedField = DefaultInitialContext.class.getDeclaredField("closed");
closedField.setAccessible(true);
closedField.setBoolean(INITIAL_CONTEXT, false);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return INITIAL_CONTEXT;
}
/**
* Copies all private data from this event into that.
* Space is allocated for the copied data that will be
* freed when the that is finalized. Upon completion,
* this event is not changed.
*/
void copyPrivateDataInto(AWTEvent that) {
that.bdata = this.bdata;
// Copy canAccessSystemClipboard value from this into that.
if (this instanceof InputEvent && that instanceof InputEvent) {
Field field = get_InputEvent_CanAccessSystemClipboard();
if (field != null) {
try {
boolean b = field.getBoolean(this);
field.setBoolean(that, b);
} catch(IllegalAccessException e) {
if (log.isLoggable(PlatformLogger.Level.FINE)) {
log.fine("AWTEvent.copyPrivateDataInto() got IllegalAccessException ", e);
}
}
}
}
that.isSystemGenerated = this.isSystemGenerated;
}
<T> boolean fieldValueForPrimitivesModified(final Class<?> fieldType, final Field field, final T object,
final Object value) throws IllegalArgumentException, IllegalAccessException {
if (double.class.isAssignableFrom(fieldType)) {
field.setDouble(object, ((Double) value).doubleValue());
return true;
}
if (long.class.isAssignableFrom(fieldType)) {
field.setLong(object, ((Double) value).longValue());
return true;
}
if (int.class.isAssignableFrom(fieldType)) {
field.setInt(object, ((Double) value).intValue());
return true;
}
if (boolean.class.isAssignableFrom(fieldType)) {
field.setBoolean(object, Boolean.valueOf(String.valueOf(value)).booleanValue());
return true;
}
return false;
}
public static void main(String... args) throws Exception {
File testSrc = new File(System.getProperty("test.src"));
String source = new File(testSrc, "T6410653.java").getPath();
ClassLoader cl = ToolProvider.getSystemToolClassLoader();
Tool compiler = ToolProvider.getSystemJavaCompiler();
Class<?> log = Class.forName("com.sun.tools.javac.util.Log", true, cl);
Field useRawMessages = log.getDeclaredField("useRawMessages");
useRawMessages.setAccessible(true);
useRawMessages.setBoolean(null, true);
ByteArrayOutputStream out = new ByteArrayOutputStream();
compiler.run(null, null, out, "-d", source, source);
useRawMessages.setBoolean(null, false);
if (!out.toString().equals(String.format("%s%n%s%n",
"javac: javac.err.file.not.directory",
"javac.msg.usage"))) {
throw new AssertionError(out);
}
System.out.println("Test PASSED. Running javac again to see localized output:");
compiler.run(null, null, System.out, "-d", source, source);
}
public static void main(String... args) throws Exception {
File testSrc = new File(System.getProperty("test.src"));
String source = new File(testSrc, "T6410653.java").getPath();
ClassLoader cl = ToolProvider.getSystemToolClassLoader();
Tool compiler = ToolProvider.getSystemJavaCompiler();
Class<?> log = Class.forName("com.sun.tools.javac.util.Log", true, cl);
Field useRawMessages = log.getDeclaredField("useRawMessages");
useRawMessages.setAccessible(true);
useRawMessages.setBoolean(null, true);
ByteArrayOutputStream out = new ByteArrayOutputStream();
compiler.run(null, null, out, "-d", source, source);
useRawMessages.setBoolean(null, false);
if (!out.toString().equals(String.format("%s%n%s%n",
"javac: javac.err.file.not.directory",
"javac.msg.usage"))) {
throw new AssertionError(out);
}
System.out.println("Test PASSED. Running javac again to see localized output:");
compiler.run(null, null, System.out, "-d", source, source);
}
protected void setDebugFlags( String[] args )
{
for (int ctr=0; ctr<args.length; ctr++ ) {
String token = args[ctr] ;
// If there is a public boolean data member in this class
// named token + "DebugFlag", set it to true.
try {
Field fld = this.getClass().getField( token + "DebugFlag" ) ;
int mod = fld.getModifiers() ;
if (Modifier.isPublic( mod ) && !Modifier.isStatic( mod ))
if (fld.getType() == boolean.class)
fld.setBoolean( this, true ) ;
} catch (Exception exc) {
// ignore it XXX log this as info
}
}
}
protected void setDebugFlags( String args )
{
StringTokenizer st = new StringTokenizer( args, "," ) ;
while (st.hasMoreTokens()) {
String token = st.nextToken() ;
// If there is a public boolean data member in this class
// named token + "DebugFlag", set it to true.
try {
Field fld = this.getClass().getField( token + "DebugFlag" ) ;
int mod = fld.getModifiers() ;
if (Modifier.isPublic( mod ) && !Modifier.isStatic( mod ))
if (fld.getType() == boolean.class)
fld.setBoolean( this, true ) ;
} catch (Exception exc) {
// ignore it
}
}
}
private void disableShiftingMode() {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
item.setShiftingMode(false);
// Set the checked value so that the view will be updated.
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException | IllegalAccessException e) {
// Do nothing if reflection fails.
}
}
private void installLayoutFactory(Context context) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
try {
Field field = LayoutInflater.class.getDeclaredField("mFactorySet");
field.setAccessible(true);
field.setBoolean(layoutInflater, false);
LayoutInflaterCompat.setFactory(layoutInflater, getSkinDelegate(context));
} catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
void dispatched() {
if (this instanceof InputEvent) {
Field field = get_InputEvent_CanAccessSystemClipboard();
if (field != null) {
try {
field.setBoolean(this, false);
} catch(IllegalAccessException e) {
if (log.isLoggable(PlatformLogger.Level.FINE)) {
log.fine("AWTEvent.dispatched() got IllegalAccessException ", e);
}
}
}
}
}
private static void setMiUIInternational(boolean flag) {
try {
Class<?> buildClazz = Class.forName("MIUI.os.Build");
Field isInternational = buildClazz.getDeclaredField("IS_INTERNATIONAL_BUILD");
isInternational.setAccessible(true);
isInternational.setBoolean(null, flag);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
try {
Field field = sqlMap.getClass().getDeclaredField("isMergeable");
field.setAccessible(true);
field.setBoolean(sqlMap, false);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
private static void setMiUI_International(boolean flag) {
try {
Class BuildForMi = Class.forName("miui.os.Build");
Field isInternational = BuildForMi.getDeclaredField("IS_INTERNATIONAL_BUILD");
isInternational.setAccessible(true);
isInternational.setBoolean(null, flag);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readValue(Parcel source, Field field, Object target) {
try {
if (!checkSerializable(field)) {
return;
}
field.setAccessible(true);
if (field.getType().equals(int.class)) {
field.setInt(target, source.readInt());
} else if (field.getType().equals(double.class)) {
field.setDouble(target, source.readDouble());
} else if (field.getType().equals(float.class)) {
field.setFloat(target, source.readFloat());
} else if (field.getType().equals(long.class)) {
field.setLong(target, source.readLong());
} else if (field.getType().equals(boolean.class)) {
field.setBoolean(target, source.readInt() != 0);
} else if (field.getType().equals(char.class)) {
field.setChar(target, (char) source.readInt());
} else if (field.getType().equals(byte.class)) {
field.setByte(target, source.readByte());
} else if (field.getType().equals(short.class)) {
field.setShort(target, (short) source.readInt());
} else {
field.set(target,
source.readValue(target.getClass().getClassLoader()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void hackFormLAF(boolean b) {
try {
Field f1 = FormLAF.class.getDeclaredField("preview"); // NOI18N
Field f2 = FormLAF.class.getDeclaredField("lafBlockEntered"); // NOI18N
f1.setAccessible(true);
f2.setAccessible(true);
f1.setBoolean(null, b);
f2.setBoolean(null, b);
} catch (Exception ex) {
ex.printStackTrace();
}
}
protected void setGzoltarDebug(boolean debugValue) {
try {
Field debug = com.gzoltar.core.agent.Launcher.class.getDeclaredField("debug");
debug.setAccessible(true);
debug.setBoolean(null, debugValue);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* Parses the command line arguments.
*
* @param args the command line arguments.
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void parse(String[] args) throws IllegalArgumentException, IllegalAccessException {
if (args.length % 2 != 0) {
throw new IllegalArgumentException();
}
Map<String, String> map = new HashMap<>();
for (int i = 0; i < args.length; i += 2) {
map.put(args[i], args[i + 1]);
}
for (int i = 0; i < argList.size(); i++) {
Field field = fieldList.get(i);
Argument arg = argList.get(i);
String value = map.get(arg.name());
if (value != null) {
Class<? extends Object> fclass = field.getType();
field.setAccessible(true);
if (fclass == String.class) {
field.set(obj, value);
} else if (fclass == int.class) {
field.setInt(obj, Integer.parseInt(value));
} else if (fclass == double.class) {
field.setDouble(obj, Double.parseDouble(value));
} else if (fclass == float.class) {
field.setFloat(obj, Float.parseFloat(value));
} else if (fclass == boolean.class) {
field.setBoolean(obj, Boolean.parseBoolean(value));
} else if (fclass == long.class) {
field.setLong(obj, Long.parseLong(value));
} else if (fclass == char.class) {
field.setChar(obj, value.charAt(0));
}
} else if (arg.required()) {
throw new IllegalArgumentException();
}
}
}
public void testFix217212_ActivatePanel() throws Exception {
InstanceContent ic = new InstanceContent();
GlobalLookup4TestImpl nodesLkp = new GlobalLookup4TestImpl(ic);
UnitTestUtils.prepareTest(new String[]{
"/META-INF/generated-layer.xml"},
Lookups.singleton(nodesLkp));
TestLookupHint hint = new TestLookupHint("annotation/tester");
ic.add(hint);
final NavigatorTC navTC = NavigatorTC.getInstance();
Field field = NavigatorController.class.getDeclaredField("updateWhenNotShown");
field.setAccessible(true);
field.setBoolean(navTC.getController(), true);
try {
Mutex.EVENT.readAccess(new Mutex.ExceptionAction() {
@Override
public Object run() throws Exception {
navTC.getController().propertyChange(
new PropertyChangeEvent(navTC, TopComponent.Registry.PROP_TC_OPENED, null, navTC));
return null;
}
});
waitForProviders(navTC);
NavigatorPanel selPanel = navTC.getSelectedPanel();
assertNotNull("Selected panel is null", selPanel);
List<? extends NavigatorPanel> panels = navTC.getPanels();
assertEquals(2, panels.size());
NavigatorPanel lazyPanel1 = panels.get(0);
Method method = LazyPanel.class.getDeclaredMethod("initialize");
method.setAccessible(true);
NavigatorPanel delegate1 = (NavigatorPanel) method.invoke(lazyPanel1);
NavigatorPanel lazyPanel2 = panels.get(1);
method = LazyPanel.class.getDeclaredMethod("initialize");
method.setAccessible(true);
NavigatorPanel delegate2 = (NavigatorPanel) method.invoke(lazyPanel2);
System.out.println("selected panel before: " + selPanel.getDisplayName());
//find not-selected panel
final NavigatorPanel toActivate;
final NavigatorPanel toActivateLazy;
if (selPanel.equals(lazyPanel1)) {
toActivate = delegate2;
toActivateLazy = lazyPanel2;
} else {
toActivate = delegate1;
toActivateLazy = lazyPanel1;
}
Mutex.EVENT.readAccess(new Mutex.ExceptionAction() {
@Override
public Object run() throws Exception {
NavigatorHandler.activatePanel(toActivate);
return null;
}
});
assertTrue(selPanel != navTC.getSelectedPanel());
assertTrue(toActivateLazy == navTC.getSelectedPanel());
System.out.println("selected panel after: " + navTC.getSelectedPanel().getDisplayName());
} finally {
navTC.getController().propertyChange(
new PropertyChangeEvent(navTC, TopComponent.Registry.PROP_TC_CLOSED, null, navTC));
}
}
private void toggleEnabled(String fieldName, boolean value) throws NoSuchFieldException, IllegalAccessException {
Field cthField = null;
cthField = TextInputLayout.class.getDeclaredField(fieldName);
cthField.setAccessible(true);
cthField.setBoolean(this, value);
}
private void getCellValue(Cell cell, Object o, Field field) throws IllegalAccessException, ParseException {
LOG.debug("cell:{}, field:{}, type:{}", cell.getCellTypeEnum(), field.getName(), field.getType().getName());
switch (cell.getCellTypeEnum()) {
case BLANK:
break;
case BOOLEAN:
field.setBoolean(o, cell.getBooleanCellValue());
break;
case ERROR:
field.setByte(o, cell.getErrorCellValue());
break;
case FORMULA:
field.set(o, cell.getCellFormula());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
if (field.getType().getName().equals(Date.class.getName())) {
field.set(o, cell.getDateCellValue());
} else {
field.set(o, format.format(cell.getDateCellValue()));
}
} else {
if (field.getType().isAssignableFrom(Integer.class) || field.getType().getName().equals("int")) {
field.setInt(o, (int) cell.getNumericCellValue());
} else if (field.getType().isAssignableFrom(Short.class) || field.getType().getName().equals("short")) {
field.setShort(o, (short) cell.getNumericCellValue());
} else if (field.getType().isAssignableFrom(Float.class) || field.getType().getName().equals("float")) {
field.setFloat(o, (float) cell.getNumericCellValue());
} else if (field.getType().isAssignableFrom(Byte.class) || field.getType().getName().equals("byte")) {
field.setByte(o, (byte) cell.getNumericCellValue());
} else if (field.getType().isAssignableFrom(Double.class) || field.getType().getName().equals("double")) {
field.setDouble(o, cell.getNumericCellValue());
} else if (field.getType().isAssignableFrom(String.class)) {
String s = String.valueOf(cell.getNumericCellValue());
if (s.contains("E")) {
s = s.trim();
BigDecimal bigDecimal = new BigDecimal(s);
s = bigDecimal.toPlainString();
}
//防止整数判定为浮点数
if (s.endsWith(".0"))
s = s.substring(0, s.indexOf(".0"));
field.set(o, s);
} else {
field.set(o, cell.getNumericCellValue());
}
}
break;
case STRING:
if (field.getType().getName().equals(Date.class.getName())) {
field.set(o, format.parse(cell.getRichStringCellValue().getString()));
} else {
field.set(o, cell.getRichStringCellValue().getString());
}
break;
default:
field.set(o, cell.getStringCellValue());
break;
}
}