private static void initialize(TypeDataBase db) { if (VM.getVM().isServerCompiler()) { Type type = db.lookupType("Matcher"); Field f = type.getField("_regEncode"); matcherRegEncodeAddr = f.getStaticFieldAddress(); } }
public Matrix createVector(BitVector selector) { int rows = selector != null ? selector.countOnBits() : frame.size(); Matrix m = new Matrix(rows, 1); for (int i = 0, j = 0; j < frame.size(); j++) { if (selector == null || selector.isOn(j)) { M rowValue = frame.object(j); try { Number numValue = (Number) numericField.get(rowValue); m.set(i, 0, numValue.doubleValue()); } catch (IllegalAccessException e) { e.printStackTrace(); throw new IllegalStateException( String.format( "Couldn't access field %s: %s", numericField.getName(), e.getMessage())); } i++; } } return m; }
protected void _addFields(Map<String, AnnotatedField> fields, Class<?> c) { /* First, a quick test: we only care for regular classes (not * interfaces, primitive types etc), except for Object.class. * A simple check to rule out other cases is to see if there * is a super class or not. */ Class<?> parent = c.getSuperclass(); if (parent != null) { // Let's add super-class' fields first, then ours. /* 21-Feb-2010, tatu: Need to handle masking: as per [JACKSON-226] * we otherwise get into trouble... */ _addFields(fields, parent); for (Field f : c.getDeclaredFields()) { // static fields not included, nor transient if (!_isIncludableField(f)) { continue; } /* Ok now: we can (and need) not filter out ignorable fields * at this point; partly because mix-ins haven't been * added, and partly because logic can be done when * determining get/settability of the field. */ fields.put(f.getName(), _constructField(f)); } // And then... any mix-in overrides? if (_mixInResolver != null) { Class<?> mixin = _mixInResolver.findMixInClassFor(c); if (mixin != null) { _addFieldMixIns(mixin, fields); } } } }
static { HashMap<String, Field> map = new HashMap<>(); for (Field field : Field.values()) { map.put(field.getName(), field); } byName = map; }
/** * オブジェクトのフィールドにデータを設定する<br> * Integer、Float、Float[]、Stringにしか対応していない * * @param obj 設定対象オブジェクト * @param fl 設定対象フィールド * @param ty 設定対象フィールドの型 * @param data 設定データ * @throws IllegalArgumentException * @throws IllegalAccessException */ protected void dataSetter(Object obj, Field fl, Class ty, String data) throws IllegalArgumentException, IllegalAccessException { // Integer型のデータを設定 if (ty.toString().equals("class java.lang.Integer")) { fl.set(obj, Integer.parseInt(data)); } // Float型のデータを設定 if (ty.toString().equals("class java.lang.Float")) { fl.set(obj, Float.parseFloat(data)); } // String型のデータを設定(""の内側) if (ty.toString().equals("class java.lang.String")) { fl.set(obj, getDoubleQuoatString(data)); } // Float[]型のデータを設定 if (ty.toString().equals("class [Ljava.lang.Float;")) { String[] s; s = data.split(" "); Float[] f = new Float[s.length]; for (int i = 0; i < s.length; i++) { f[i] = Float.parseFloat(s[i]); } fl.set(obj, f); } }
/** Check that the assignment to a field is correct. */ protected void checkFieldAssign( FlowGraph graph, FieldAssign a, DataFlowItem dfIn, DataFlowItem dfOut) throws SemanticException { Field f = (Field) a.left(); FieldInstance fi = f.fieldInstance(); if (fi.flags().isFinal()) { if ((currCBI.currCodeDecl instanceof ConstructorDecl || currCBI.currCodeDecl instanceof Initializer) && isFieldsTargetAppropriate(f)) { // we are in a constructor or initializer block and // if the field is static then the target is the class // at hand, and if it is not static then the // target of the field is this. // So a final field in this situation can be // assigned to at most once. MinMaxInitCount initCount = (MinMaxInitCount) dfOut.initStatus.get(fi); if (InitCount.MANY.equals(initCount.getMax())) { throw new SemanticException( "field \"" + fi.name() + "\" might already have been assigned to", a.position()); } } else { // not in a constructor or intializer, or the target is // not appropriate. So we cannot assign // to a final field at all. throw new SemanticException( "Cannot assign a value " + "to final field \"" + fi.name() + "\"", a.position()); } } }
@NotNull private static List<Parameter> createParametersFromFields(@NotNull List<? extends Field> fields) { List<Parameter> result = new LinkedList<Parameter>(); for (Field f : fields) result.add(new Parameter(new IdentifierImpl("_" + f.getIdentifier().getName()), f.getType())); return result; }
void instantiateWithInjectableValues(@Nonnull Object testClassInstance) { if (isAvailableDuringSetup() && getFieldValue(testedField, testClassInstance) != null) { return; } injectionState.setTestedField(testedField); Object testedObject = getTestedObjectFromFieldInTestClassIfApplicable(testClassInstance); Class<?> testedClass = testedField.getType(); if (testedObject == null && createAutomatically) { if (reusePreviouslyCreatedInstance(testClassInstance, testedClass)) { return; } if (testedObjectCreation != null) { testedObject = testedObjectCreation.create(); setFieldValue(testedField, testClassInstance, testedObject); injectionState.saveTestedObject(testedClass, testedObject); } } else if (testedObject != null) { String dependencyKey = InjectionPoint.dependencyKey(testedClass, testedField.getName()); injectionState.saveTestedObject(dependencyKey, testedObject); testedClass = testedObject.getClass(); } if (testedObject != null) { performFieldInjection(testedClass, testedObject); executeInitializationMethodsIfAny(testedClass, testedObject); } }
private void validateClass(Class<?> source, ValidationProblemCollector problems) { int modifiers = source.getModifiers(); if (Modifier.isInterface(modifiers)) { problems.add("Must be a class, not an interface"); } if (source.getEnclosingClass() != null) { if (Modifier.isStatic(modifiers)) { if (Modifier.isPrivate(modifiers)) { problems.add("Class cannot be private"); } } else { problems.add("Enclosed classes must be static and non private"); } } Constructor<?>[] constructors = source.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length > 0) { problems.add("Cannot declare a constructor that takes arguments"); break; } } Field[] fields = source.getDeclaredFields(); for (Field field : fields) { int fieldModifiers = field.getModifiers(); if (!field.isSynthetic() && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) { problems.add(field, "Fields must be static final."); } } }
/** * This method returns the maximum representation size of an object. <code>sizeSoFar</code> is the * object's size measured so far. <code>f</code> is the field being probed. * * <p>The returned offset will be the maximum of whatever was measured so far and <code>f</code> * field's offset and representation size (unaligned). */ private static long adjustForField(long sizeSoFar, final Field f) { final Class<?> type = f.getType(); final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF; if (objectFieldOffsetMethod != null) { try { final long offsetPlusSize = ((Number) objectFieldOffsetMethod.invoke(theUnsafe, f)).longValue() + fsize; return Math.max(sizeSoFar, offsetPlusSize); } catch (IllegalAccessException ex) { throw new RuntimeException("Access problem with sun.misc.Unsafe", ex); } catch (InvocationTargetException ite) { final Throwable cause = ite.getCause(); if (cause instanceof RuntimeException) throw (RuntimeException) cause; if (cause instanceof Error) throw (Error) cause; // this should never happen (Unsafe does not declare // checked Exceptions for this method), but who knows? throw new RuntimeException( "Call to Unsafe's objectFieldOffset() throwed " + "checked Exception when accessing field " + f.getDeclaringClass().getName() + "#" + f.getName(), cause); } } else { // TODO: No alignments based on field type/ subclass fields alignments? return sizeSoFar + fsize; } }
private void setDNAndEntryFields(final T o, final Entry e) throws LDAPPersistException { if (dnField != null) { try { dnField.set(o, e.getDN()); } catch (Exception ex) { debugException(ex); throw new LDAPPersistException( ERR_OBJECT_HANDLER_ERROR_SETTING_DN.get( type.getName(), e.getDN(), dnField.getName(), getExceptionMessage(ex)), ex); } } if (entryField != null) { try { entryField.set(o, new ReadOnlyEntry(e)); } catch (Exception ex) { debugException(ex); throw new LDAPPersistException( ERR_OBJECT_HANDLER_ERROR_SETTING_ENTRY.get( type.getName(), entryField.getName(), getExceptionMessage(ex)), ex); } } }
public static void writeParam(String xNameFile) { // // write to file xpar all parameters..... // IOseq xFile; xFile = new IOseq(xNameFile); xFile.IOseqOpenW(false); try { Class c = Class.forName("jneat.Neat"); Field[] fieldlist = c.getDeclaredFields(); for (int i = 0; i < fieldlist.length; i++) { Field f1 = fieldlist[i]; String x1 = f1.getName(); if (x1.startsWith("p_")) { Field f2 = c.getField("d_" + Neat.normalizeName(x1)); Object s1 = f1.get(c); Object s2 = f2.get(c); // String riga = s1 + " " + s2; String riga = x1 + " " + s1; xFile.IOseqWrite(riga); } } } catch (Throwable e) { System.err.println(e); } xFile.IOseqCloseW(); }
private ArrayList<Element> serializeFields( Field[] fields, Object object, Document doc) // serializes the fields { Class currentClass = object.getClass(); ArrayList<Element> elements = new ArrayList<Element>(); for (Field f : fields) { try { if (!f.getType().isPrimitive()) // Field not primitive, is a reference to another object { } else // field is primitive { Element newField = new Element("field"); newField.setAttribute("name", f.getName()); newField.setAttribute("declaringclass", f.getDeclaringClass().getName()); Element newValue = new Element("value"); newValue.addContent(f.get(object).toString()); newField.addContent(newValue); elements.add(newField); } } catch (Exception e) { e.printStackTrace(); } } return elements; }
void put(Scriptable scope, String name, Object javaObject, Object value, boolean isStatic) { Map<String, Object> ht = isStatic ? staticMembers : members; Object member = ht.get(name); if (!isStatic && member == null) { // Try to get static member from instance (LC3) member = staticMembers.get(name); } if (member == null) throw reportMemberNotFound(name); if (member instanceof FieldAndMethods) { FieldAndMethods fam = (FieldAndMethods) ht.get(name); member = fam.field; } // Is this a bean property "set"? if (member instanceof BeanProperty) { BeanProperty bp = (BeanProperty) member; if (bp.setter == null) { throw reportMemberNotFound(name); } // If there's only one setter or if the value is null, use the // main setter. Otherwise, let the NativeJavaMethod decide which // setter to use: if (bp.setters == null || value == null) { Class<?> setType = bp.setter.argTypes[0]; Object[] args = {Context.jsToJava(value, setType)}; try { bp.setter.invoke(javaObject, args); } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } } else { Object[] args = {value}; bp.setters.call( Context.getContext(), ScriptableObject.getTopLevelScope(scope), scope, args); } } else { if (!(member instanceof Field)) { String str = (member == null) ? "msg.java.internal.private" : "msg.java.method.assign"; throw Context.reportRuntimeError1(str, name); } Field field = (Field) member; Object javaValue = Context.jsToJava(value, field.getType()); try { field.set(javaObject, javaValue); } catch (IllegalAccessException accessEx) { if ((field.getModifiers() & Modifier.FINAL) != 0) { // treat Java final the same as JavaScript [[READONLY]] return; } throw Context.throwAsScriptRuntimeEx(accessEx); } catch (IllegalArgumentException argEx) { throw Context.reportRuntimeError3( "msg.java.internal.field.type", value.getClass().getName(), field, javaObject.getClass().getName()); } } }
/** * Returns a class' static attribute value * * @param objectType the class to query * @param attributeName the name of the attribute * @return the attribute value */ public static Object getStaticAttributeValue(Class<?> objectType, String attributeName) { Field field = getField(objectType, attributeName); try { return field.get(null); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, field); } }
/** * Determine if we are interested in this field on the basis of the target of the field. To wit, * if the field is static, then the target of the field must be the current class; if the field is * not static then the target must be "this". */ protected boolean isFieldsTargetAppropriate(Field f) { if (f.fieldInstance().flags().isStatic()) { ClassType containingClass = (ClassType) currCBI.currCodeDecl.codeInstance().container(); return containingClass.equals(f.fieldInstance().container()); } else { return (f.target() instanceof Special && Special.THIS.equals(((Special) f.target()).kind())); } }
/** * Generates a byte array representing the contents of this page. Used to serialize this page to * disk. * * <p>The invariant here is that it should be possible to pass the byte array generated by * getPageData to the HeapPage constructor and have it produce an identical HeapPage object. * * @see #HeapPage * @return A byte array correspond to the bytes of this page. */ public byte[] getPageData() { // int len = header.length*4 + BufferPool.PAGE_SIZE; int len = BufferPool.PAGE_SIZE; ByteArrayOutputStream baos = new ByteArrayOutputStream(len); DataOutputStream dos = new DataOutputStream(baos); // create the header of the page try { dos.write(header.getHeader()); } catch (IOException e) { // this really shouldn't happen e.printStackTrace(); } // create the tuples for (int i = 0; i < numSlots; i++) { // empty slot if (!getSlot(i)) { for (int j = 0; j < td.getSize(); j++) { try { dos.writeByte(0); } catch (IOException e) { e.printStackTrace(); } } continue; } // non-empty slot for (int j = 0; j < td.numFields(); j++) { Field f = tuples[i].getField(j); try { f.serialize(dos); } catch (IOException e) { e.printStackTrace(); } } } // padding int zerolen = BufferPool.PAGE_SIZE - numSlots * td.getSize() - header.length(); byte[] zeroes = new byte[zerolen]; try { dos.write(zeroes, 0, zerolen); } catch (IOException e) { e.printStackTrace(); } try { dos.flush(); } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); }
@NotNull private static List<Field> getFinalOrWithEmptyInitializer(@NotNull List<? extends Field> fields) { List<Field> result = new LinkedList<Field>(); for (Field f : fields) if (f.isVal() || f.getInitializer().toKotlin().isEmpty()) { result.add(f); } return result; }
/** * Returns an object's attribute value * * @param obj the object to query * @param attributeName the name of the attribute * @return the attribute value */ public static Object getAttributeValue(Object obj, String attributeName) { if (obj == null) throw new IllegalArgumentException("Object may not be null"); Field field = getField(obj.getClass(), attributeName); try { return field.get(obj); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, field); } }
public static String getDescription(String xkey) { try { Class c = Class.forName("jneat.Neat"); Field f = c.getField("d_" + xkey); return (String) f.get(c); } catch (Throwable e) { return null; } }
private Statement getOriginalStatement(Statement methodInvoker, Field field) { field.setAccessible(true); try { return (Statement) field.get(methodInvoker); } catch (Exception e) { e.printStackTrace(); return null; } }
private String field(Issue issue, TicketFields filed) { Field field = issue.getFieldByName(filed.getName()); if (field != null) { Object fieldValue = field.getValue(); if (fieldValue != null) { return fieldValue.toString(); } } return ""; }
@NotNull private static List<Statement> createInitStatementsFromFields( @NotNull List<? extends Field> fields) { List<Statement> result = new LinkedList<Statement>(); for (Field f : fields) { String identifierToKotlin = f.getIdentifier().toKotlin(); result.add(new DummyStringExpression(identifierToKotlin + " = " + "_" + identifierToKotlin)); } return result; }
public static Object getFieldValue(Field field, Object target, boolean strict) { try { if ((field.getModifiers() & Modifier.STATIC) == Modifier.STATIC) return field.get(null); else return field.get(target); } catch (IllegalArgumentException e) { throw new ConfigurationError(e); } catch (IllegalAccessException e) { throw new ConfigurationError(e); } }
// Use reflection to get version since early versions // of ImageJ do not have the IJ.getVersion() method. String version() { String version = ""; try { Class ijClass = ImageJ.class; Field field = ijClass.getField("VERSION"); version = (String) field.get(ijClass); } catch (Exception ex) { } return version; }
private void findTestedAndInjectableFields(@NotNull Field[] fieldsDeclaredInTestClass) { for (Field field : fieldsDeclaredInTestClass) { if (field.isAnnotationPresent(Injectable.class)) { MockedType mockedType = new MockedType(field); injectableFields.add(mockedType); } else { addAsTestedFieldIfApplicable(field); } } }
@SuppressWarnings("unchecked") private void addFields(List list, boolean isStatic) { int count = klass.getFieldCount(isStatic); for (int i = 0; i != count; ++i) { Field field = klass.getField(i, isStatic); FieldID fid = new FieldID(JDWP.getTag(field.getType()), field.getOffset(), isStatic, getID()); ProxyField proxyField = new ProxyField(fid, field); list.add(proxyField); } }
public Object getChild(Object parent, int index) { ArrayList<Field> fields = ((Variable) parent).getFields(); Field f = (Field) fields.get(index); Object parentValue = ((Variable) parent).getValue(); try { return new Variable(f.getType(), f.getName(), f.get(parentValue)); } catch (IllegalAccessException e) { return null; } }
public static void setEnv(Map<String, String> newenv) { try { Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment"); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); } catch (NoSuchFieldException e) { try { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for (Class cl : classes) { if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } } } catch (Exception e2) { e2.printStackTrace(); } } catch (Exception e1) { e1.printStackTrace(); } }
public static Properties getParent(Properties p) { try { Field f = Properties.class.getDeclaredField("defaults"); f.setAccessible(true); return (Properties) f.get(p); } catch (Exception e) { Field[] fields = Properties.class.getFields(); System.err.println(Arrays.toString(fields)); return null; } }