Java Code Examples for java.lang.reflect.Field#getShort()

The following examples show how to use java.lang.reflect.Field#getShort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CoffMachineType.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Checks to see if the given machine type is defined in this file.
 * 
 * @param type The machine type to check.
 * @return True if the given machine type is defined in this file; otherwise, false.
 */
public static boolean isMachineTypeDefined(short type) {
	if (type == IMAGE_FILE_MACHINE_UNKNOWN) {
		// This machine type is only defined in this file for completeness.
		// We want to treat this type as an unsupported machine.
		return false;
	}

	for (Field field : CoffMachineType.class.getDeclaredFields()) {
		if (!field.isSynthetic()) {
			int modifiers = field.getModifiers();
			if (Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers)) {
				try {
					if (field.getShort(null) == type) {
						return true;
					}
				}
				catch (IllegalAccessException e) {
					continue;
				}
			}
		}
	}
	return false;
}
 
Example 2
Source File: TestInstanceCloneUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
int getVal(Field f) {
    try {
        if (f.getType() == int.class) {
            return f.getInt(this);
        } else if (f.getType() == short.class) {
            return (int)f.getShort(this);
        } else if (f.getType() == byte.class) {
            return (int)f.getByte(this);
        } else if (f.getType() == long.class) {
            return (int)f.getLong(this);
        }
    } catch(IllegalAccessException iae) {
        throw new RuntimeException("Setting fields failed");
    }
    throw new RuntimeException("unexpected field type");
}
 
Example 3
Source File: CoreMacOSX.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public static String FileManager_findFolder(boolean isUserDomain, String folderType) {
	try {
		Class<?> FileManagerClass = Class.forName("com.apple.eio.FileManager"); //$NON-NLS-1$
		Method findFolderMethod = FileManagerClass.getMethod("findFolder", new Class[] { short.class, int.class }); //$NON-NLS-1$
		Method OSTypeToIntMethod = FileManagerClass.getMethod("OSTypeToInt", new Class[] { String.class }); //$NON-NLS-1$
		Field kUserDomainField = FileManagerClass.getField("kUserDomain"); //$NON-NLS-1$
		Field kSystemDomainField = FileManagerClass.getField("kSystemDomain"); //$NON-NLS-1$

		short domain = isUserDomain ? kUserDomainField.getShort(FileManagerClass) : kSystemDomainField.getShort(FileManagerClass);
		int type = ((Integer) OSTypeToIntMethod.invoke(FileManagerClass, new Object[] { folderType })).intValue();
		return (String) findFolderMethod.invoke(FileManagerClass, new Object[] { domain, type });
	} catch (Exception e) {
		IdeLog.logError(CorePlugin.getDefault(), e);
	}
	return null;
}
 
Example 4
Source File: LinuxInput.java    From Monocle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Convert an event code to its equivalent string, given its type string.
 * The type string is needed because event codes are context sensitive. For
 * example, the code 1 is "SYN_CONFIG" for an EV_SYN event but "KEY_ESC" for
 * an EV_KEY event.  This method is inefficient and is for debugging use
 * only.
 */
static String codeToString(String type, short code) {
    int i = type.indexOf("_");
    if (i >= 0) {
        String prefix = type.substring(i + 1);
        String altPrefix = prefix.equals("KEY") ? "BTN" : prefix;
        for (Field field : LinuxInput.class.getDeclaredFields()) {
            String name = field.getName();
            try {
                if ((name.startsWith(prefix) || name.startsWith(altPrefix))
                        && field.getType() == Short.TYPE
                        && field.getShort(null) == code) {
                    return field.getName();
                }
            } catch (IllegalAccessException e) {
            }
        }
    }
    return new Formatter().format("0x%04x", code & 0xffff).out().toString();
}
 
Example 5
Source File: MapItemTypeCodes.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public final static String toString( short type ) {
	try {
		Field [] fields = MapItemTypeCodes.class.getDeclaredFields( );
		for ( Field field : fields ) {
			if ( field.getShort( null ) == type ) {
				return field.getName( );
			}
		}
	}
	catch ( Exception e ) {
		// ignore
	}
	return "Type:" + type;
}
 
Example 6
Source File: RakNetPacket.java    From JRakNet with MIT License 5 votes vote down vote up
/**
 * Maps all <code>public</code> packet IDs to their respective field names
 * and vice-versa.
 * <p>
 * Packet IDs {@link #ID_CUSTOM_0}, {@link #ID_CUSTOM_1},
 * {@link #ID_CUSTOM_2}, {@link #ID_CUSTOM_3}, {@link #ID_CUSTOM_4},
 * {@link #ID_CUSTOM_5}, {@link #ID_CUSTOM_6}, {@link #ID_CUSTOM_7},
 * {@link #ID_CUSTOM_8}, {@link #ID_CUSTOM_9}, {@link #ID_CUSTOM_A},
 * {@link #ID_CUSTOM_B}, {@link #ID_CUSTOM_C}, {@link #ID_CUSTOM_D},
 * {@link #ID_CUSTOM_E}, {@link #ID_CUSTOM_F}, {@link #ID_ACK}, and
 * {@link #ID_NACK} are ignored as they are not only internal packets but
 * they also override other packets with the same ID.
 */
private static void mapNameIds() {
	if (mappedNameIds == false) {
		Logger log = LogManager.getLogger(RakNetPacket.class);
		for (Field field : RakNetPacket.class.getFields()) {
			if (field.getType().equals(short.class)) {
				try {
					short packetId = field.getShort(null);
					if ((packetId >= ID_CUSTOM_0 && packetId <= ID_CUSTOM_F) || packetId == ID_ACK
							|| packetId == ID_NACK) {
						continue; // Ignored as they override other packet
									// IDs
					}
					String packetName = field.getName();
					String currentName = PACKET_NAMES.put(packetId, packetName);
					PACKET_IDS.put(packetName, packetId);
					if (currentName != null) {
						if (!currentName.equals(packetName)) {
							log.warn("Found duplicate ID " + RakNet.toHexStringId(packetId) + " for \"" + packetName
									+ "\" and \"" + currentName + "\", overriding name and ID");
						}
					} else {
						log.debug("Assigned packet ID " + RakNet.toHexStringId(packetId) + " to " + packetName);
					}
				} catch (ReflectiveOperationException e) {
					e.printStackTrace();
				}
			}
		}
		mappedNameIds = true;
	}
}
 
Example 7
Source File: LinuxInput.java    From Monocle with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convert an event type to its equivalent string. This method is
 * inefficient and is for debugging use only.
 */
static String typeToString(short type) {
    for (Field field : LinuxInput.class.getDeclaredFields()) {
        try {
            if (field.getName().startsWith("EV_")
                    && field.getType() == Short.TYPE
                    && field.getShort(null) == type) {
                return field.getName();
            }
        } catch (IllegalAccessException e) {
        }
    }
    return new Formatter().format("0x%04x", type & 0xffff).out().toString();
}
 
Example 8
Source File: Tags.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the name of the given tag. Implementation of this method is inefficient,
 * but it should rarely be invoked (mostly for formatting error messages).
 */
static String name(final short tag) {
    try {
        for (final Field field : Tags.class.getFields()) {
            if (field.getType() == Short.TYPE) {
                if (field.getShort(null) == tag) {
                    return field.getName();
                }
            }
        }
    } catch (IllegalAccessException e) {
        throw new AssertionError(e);        // Should never happen because we asked only for public fields.
    }
    return Integer.toHexString(Short.toUnsignedInt(tag));
}
 
Example 9
Source File: GeoKeys.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the name of the given key. Implementation of this method is inefficient,
 * but it should rarely be invoked (mostly for formatting error messages).
 */
static String name(final short key) {
    try {
        for (final Field field : GeoKeys.class.getFields()) {
            if (field.getType() == Short.TYPE) {
                if (field.getShort(null) == key) {
                    return field.getName();
                }
            }
        }
    } catch (IllegalAccessException e) {
        throw new AssertionError(e);        // Should never happen because we asked only for public fields.
    }
    return Integer.toHexString(Short.toUnsignedInt(key));
}
 
Example 10
Source File: GeoIdentifiers.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the name of the given code. Implementation of this method is inefficient,
 * but it should rarely be invoked (mostly for formatting error messages).
 */
static String name(final short tag) {
    try {
        for (final Field field : GeoIdentifiers.class.getFields()) {
            if (field.getType() == Short.TYPE) {
                if (field.getShort(null) == tag) {
                    return field.getName();
                }
            }
        }
    } catch (IllegalAccessException e) {
        throw new AssertionError(e);        // Should never happen because we asked only for public fields.
    }
    return Integer.toHexString(Short.toUnsignedInt(tag));
}
 
Example 11
Source File: HardwareAddressImpl.java    From c2mon with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public final int hashCode() {

  int result = 0;

  Field[] fields = this.getClass().getDeclaredFields();

  for (Field field : fields) {
    // compare non-final, non-static and non-transient fields only
    if (!Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())
        && !Modifier.isTransient(field.getModifiers())) {
      try {

        // skip arrays
        if (!field.getType().isArray() && field.get(this) != null) {
          // for string take its length
          if (field.getType().equals(String.class)) {
            result ^= ((String) field.get(this)).length();
          } else if (field.getType().equals(short.class) || field.getType().equals(Short.class)) {
            result ^= field.getShort(this);
          } else if (field.getType().equals(int.class) || field.getType().equals(Integer.class)) {
            result ^= field.getInt(this);
          } else if (field.getType().equals(float.class) || field.getType().equals(Float.class)) {
            result ^= (int) field.getFloat(this);
          } else if (field.getType().equals(double.class) || field.getType().equals(Double.class)) {
            result ^= (int) field.getDouble(this);
          } else if (field.getType().equals(long.class) || field.getType().equals(Long.class)) {
            result ^= (int) field.getLong(this);
          } else if (field.getType().equals(byte.class) || field.getType().equals(Byte.class)) {
            result ^= field.getByte(this);
          } else if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) {
            result ^= field.getBoolean(this) == Boolean.TRUE ? 1 : 0;
          }
        }
      } catch (Exception e) {
        log.error(e.toString());
        throw new RuntimeException("Exception caught while calculating HardwareAddress hashcode.", e);
      }
    }
  }
  return result;
}
 
Example 12
Source File: FieldTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
Object getField(char primitiveType, Object o, Field f,
        Class expected) {
    Object res = null;
    try {
        primitiveType = Character.toUpperCase(primitiveType);
        switch (primitiveType) {
        case 'I': // int
            res = new Integer(f.getInt(o));
            break;
        case 'J': // long
            res = new Long(f.getLong(o));
            break;
        case 'Z': // boolean
            res = new Boolean(f.getBoolean(o));
            break;
        case 'S': // short
            res = new Short(f.getShort(o));
            break;
        case 'B': // byte
            res = new Byte(f.getByte(o));
            break;
        case 'C': // char
            res = new Character(f.getChar(o));
            break;
        case 'D': // double
            res = new Double(f.getDouble(o));
            break;
        case 'F': // float
            res = new Float(f.getFloat(o));
            break;
        default:
            res = f.get(o);
        }
        // Since 2011, members are always accessible and throwing is optional
        assertTrue("expected " + expected + " for " + f.getName(),
                expected == null || expected == IllegalAccessException.class);
    } catch (Exception e) {
        if (expected == null) {
            fail("unexpected exception " + e);
        } else {
            assertTrue("expected exception "
                    + expected.getName() + " and got " + e, e
                    .getClass().equals(expected));
        }
    }
    return res;
}
 
Example 13
Source File: FieldByFieldComparison.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
private static boolean matches(Class<?> type, Object left, Object right, Set<Pair> visited) throws Exception {
    if (!visited.add(new Pair(left, right))) {
        return true;
    } else if (mockingDetails(left).isMock() || mockingDetails(left).isSpy() || mockingDetails(right).isMock() || mockingDetails(right).isSpy()) {
        return left == right;
    }
    while (type.getName().startsWith("net.bytebuddy.")) {
        for (Field field : type.getDeclaredFields()) {
            if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic() && !field.getName().equals("this$0")) {
                continue;
            }
            HashCodeAndEqualsPlugin.ValueHandling valueHandling = field.getAnnotation(HashCodeAndEqualsPlugin.ValueHandling.class);
            if (valueHandling != null && valueHandling.value() == HashCodeAndEqualsPlugin.ValueHandling.Sort.IGNORE) {
                continue;
            }
            field.setAccessible(true);
            if (field.getType() == boolean.class) {
                if (field.getBoolean(left) != field.getBoolean(right)) {
                    return false;
                }
            } else if (field.getType() == byte.class) {
                if (field.getBoolean(left) != field.getBoolean(right)) {
                    return false;
                }
            } else if (field.getType() == short.class) {
                if (field.getShort(left) != field.getShort(right)) {
                    return false;
                }
            } else if (field.getType() == char.class) {
                if (field.getChar(left) != field.getChar(right)) {
                    return false;
                }
            } else if (field.getType() == int.class) {
                if (field.getInt(left) != field.getInt(right)) {
                    return false;
                }
            } else if (field.getType() == long.class) {
                if (field.getLong(left) != field.getLong(right)) {
                    return false;
                }
            } else if (field.getType() == float.class) {
                if (field.getFloat(left) != field.getFloat(right)) {
                    return false;
                }
            } else if (field.getType() == double.class) {
                if (field.getDouble(left) != field.getDouble(right)) {
                    return false;
                }
            } else if (field.getType().isEnum()) {
                if (field.get(left) != field.get(right)) {
                    return false;
                }
            } else {
                Object leftObject = field.get(left), rightObject = field.get(right);
                if (mockingDetails(leftObject).isMock() || mockingDetails(rightObject).isSpy() || mockingDetails(rightObject).isMock() || mockingDetails(rightObject).isSpy()) {
                    if (leftObject != rightObject) {
                        return false;
                    }
                } else if (Iterable.class.isAssignableFrom(field.getType())) {
                    if (rightObject == null) {
                        return false;
                    }
                    Iterator<?> rightIterable = ((Iterable<?>) rightObject).iterator();
                    for (Object instance : (Iterable<?>) leftObject) {
                        if (!rightIterable.hasNext() || !matches(instance.getClass(), instance, rightIterable.next(), visited)) {
                            return false;
                        }
                    }
                } else if (field.getType().getName().startsWith("net.bytebuddy.")) {
                    if (leftObject == null ? rightObject != null : !matches(leftObject.getClass(), leftObject, rightObject, visited)) {
                        return false;
                    }
                } else {
                    if (leftObject == null ? rightObject != null : !leftObject.equals(rightObject)) {
                        return false;
                    }
                }
            }
        }
        type = type.getSuperclass();
    }
    return true;
}