示例#1
0
 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();
   }
 }
示例#2
0
  private int findfd(Object fdObj) throws Exception {
    Class cl;
    Field f;
    Object val, implVal;

    if ((fdObj instanceof java.net.Socket) || (fdObj instanceof java.net.ServerSocket)) {
      cl = fdObj.getClass();
      f = cl.getDeclaredField("impl");
      f.setAccessible(true);
      val = f.get(fdObj);
      cl = f.getType();
      f = cl.getDeclaredField("fd");
      f.setAccessible(true);
      implVal = f.get(val);
      cl = f.getType();
      f = cl.getDeclaredField("fd");
      f.setAccessible(true);
      return ((Integer) f.get(implVal)).intValue();
    } else if (fdObj instanceof java.io.FileDescriptor) {
      cl = fdObj.getClass();
      f = cl.getDeclaredField("fd");
      f.setAccessible(true);
      return ((Integer) f.get(fdObj)).intValue();
    } else {
      throw new IllegalArgumentException("Illegal Object type.");
    }
  }
示例#3
0
 private static void netxsurgery() throws Exception {
   /* Force off NetX codebase classloading. */
   Class<?> nxc;
   try {
     nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader");
   } catch (ClassNotFoundException e1) {
     try {
       nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader");
     } catch (ClassNotFoundException e2) {
       throw (new Exception("No known NetX on classpath"));
     }
   }
   ClassLoader cl = MainFrame.class.getClassLoader();
   if (!nxc.isInstance(cl)) {
     throw (new Exception("Not running from a NetX classloader"));
   }
   Field cblf, lf;
   try {
     cblf = nxc.getDeclaredField("codeBaseLoader");
     lf = nxc.getDeclaredField("loaders");
   } catch (NoSuchFieldException e) {
     throw (new Exception("JNLPClassLoader does not conform to its known structure"));
   }
   cblf.setAccessible(true);
   lf.setAccessible(true);
   Set<Object> loaders = new HashSet<Object>();
   Stack<Object> open = new Stack<Object>();
   open.push(cl);
   while (!open.empty()) {
     Object cur = open.pop();
     if (loaders.contains(cur)) continue;
     loaders.add(cur);
     Object curl;
     try {
       curl = lf.get(cur);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
     for (int i = 0; i < Array.getLength(curl); i++) {
       Object other = Array.get(curl, i);
       if (nxc.isInstance(other)) open.push(other);
     }
   }
   for (Object cur : loaders) {
     try {
       cblf.set(cur, null);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
   }
 }
    AtomicReferenceFieldUpdaterImpl(
        Class<T> tclass, Class<V> vclass, String fieldName, Class<?> caller) {
      Field field = null;
      Class fieldClass = null;
      int modifiers = 0;
      try {
        field = tclass.getDeclaredField(fieldName);
        modifiers = field.getModifiers();
        sun.reflect.misc.ReflectUtil.ensureMemberAccess(caller, tclass, null, modifiers);
        sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
        fieldClass = field.getType();
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }

      if (vclass != fieldClass) throw new ClassCastException();
      if (vclass.isPrimitive()) throw new IllegalArgumentException("Must be reference type");

      if (!Modifier.isVolatile(modifiers))
        throw new IllegalArgumentException("Must be volatile type");

      this.cclass = (Modifier.isProtected(modifiers) && caller != tclass) ? caller : null;
      this.tclass = tclass;
      if (vclass == Object.class) this.vclass = null;
      else this.vclass = vclass;
      offset = unsafe.objectFieldOffset(field);
    }
 private static Field getReflectionSlotField(Class<?> reflectionClass) {
   try {
     Field field = reflectionClass.getDeclaredField("slot");
     field.setAccessible(true);
     return field;
   } catch (NoSuchFieldException | SecurityException e) {
     throw new GraalInternalError(e);
   }
 }
示例#6
0
  /**
   * @param methodName getter method
   * @param clazz value object class
   * @return attribute name related to the specified getter method
   */
  private String getAttributeName(String methodName, Class classType) {
    String attributeName = null;
    if (methodName.startsWith("is"))
      attributeName =
          methodName.substring(2, 3).toLowerCase()
              + (methodName.length() > 3 ? methodName.substring(3) : "");
    else
      attributeName =
          methodName.substring(3, 4).toLowerCase()
              + (methodName.length() > 4 ? methodName.substring(4) : "");

    // an attribute name "Xxxx" becomes "xxxx" and this is not correct!
    try {
      Class c = classType;
      boolean attributeFound = false;
      while (!c.equals(Object.class)) {
        try {
          c.getDeclaredField(attributeName);
          attributeFound = true;
          break;
        } catch (Throwable ex2) {
          c = c.getSuperclass();
        }
      }
      if (!attributeFound) {
        // now trying to find an attribute having the first character in upper case (e.g. "Xxxx")
        String name = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
        c = classType;
        while (!c.equals(Object.class)) {
          try {
            c.getDeclaredField(name);
            attributeFound = true;
            break;
          } catch (Throwable ex2) {
            c = c.getSuperclass();
          }
        }
        if (attributeFound) attributeName = name;
      }
    } catch (Throwable ex1) {
    }

    return attributeName;
  }
  public Operation exec(Prolog engine) {
    engine.requireFeature(Prolog.Feature.JAVA_REFLECTION, this, arg1);
    engine.setB0();

    Term a1, a2, a3;
    a1 = arg1;
    a2 = arg2;
    a3 = arg3;

    Class clazz = null;
    Object instance = null;
    Field field = null;
    Object value = null;

    try {
      // 1st. argument (atom or java term)
      a1 = a1.dereference();
      if (a1.isVariable()) {
        throw new PInstantiationException(this, 1);
      } else if (a1.isSymbol()) { // class
        clazz = Class.forName(((SymbolTerm) a1).name());
      } else if (a1.isJavaObject()) { // instance
        instance = ((JavaObjectTerm) a1).object();
        clazz = ((JavaObjectTerm) a1).getClazz();
      } else {
        throw new IllegalTypeException(this, 1, "atom_or_java", a1);
      }
      // 2nd. argument (atom)
      a2 = a2.dereference();
      if (a2.isVariable()) {
        throw new PInstantiationException(this, 2);
      } else if (!a2.isSymbol()) {
        throw new IllegalTypeException(this, 2, "atom", a2);
      }
      field = clazz.getDeclaredField(((SymbolTerm) a2).name());
      // 3rd. argument (term)
      a3 = a3.dereference();
      if (a3.isJavaObject()) value = a3.toJava();
      else value = a3;
      field.setAccessible(true);
      field.set(instance, value);
      return cont;
    } catch (ClassNotFoundException e) { // Class.forName
      throw new JavaException(this, 1, e);
    } catch (NoSuchFieldException e) { // Class.getField(..)
      throw new JavaException(this, 2, e);
    } catch (SecurityException e) { // Class.getField(..)
      throw new JavaException(this, 2, e);
    } catch (NullPointerException e) { // Class.getField(..)
      throw new JavaException(this, 2, e);
    } catch (IllegalAccessException e) { // Field.get(..)
      throw new JavaException(this, 2, e);
    } catch (IllegalArgumentException e) { // Field.get(..)
      throw new JavaException(this, 2, e);
    }
  }
示例#8
0
 private static Field getField(final Class<?> clazz, final String name) {
   try {
     final Field field = clazz.getDeclaredField(name);
     field.setAccessible(true);
     return field;
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
 /**
  * Set the current opcode. This sets four global fields: the currentOpcode, the
  * currentOpcodeArgTable, the currentFormat and the currentOpcodeSymbolicNames.
  *
  * @param opcode The IA32 architecture opcode to make the current opcode
  */
 static void setCurrentOpcode(String opcode) {
   try {
     currentOpcode = opcode;
     currentOpcodeArgTable = (int[]) opcodeArgTables.get(opcode);
     currentFormat = OperatorFormatTables.getFormat(opcode);
     Field f = formats.getDeclaredField(currentFormat + "ParameterNames");
     currentOpcodeSymbolicNames = (String[]) f.get(null);
   } catch (Throwable e) {
     throw new Error("Cannot handle Assembler opcode " + opcode, e);
   }
 }
示例#10
0
 /**
  * `获取给定对象的属性的值` `@param fieldName 属性名` `@param obj 对象`
  *
  * @return
  */
 public static Object getFieldValue(String fieldName, Object obj) {
   try {
     Class cls = obj.getClass();
     Field field = cls.getDeclaredField(fieldName);
     return field.get(obj);
   } catch (Exception e) {
     e.printStackTrace();
     print("Field access error!");
     throw new RuntimeException(e);
   }
 }
示例#11
0
 private static Field getFieldFromBean(
     Class<?> clazz, String fieldName, final Class<?> originalClass) {
   try {
     Field field = clazz.getDeclaredField(fieldName);
     // Allow access to private instance var's that dont have public setter.
     field.setAccessible(true);
     return field;
   } catch (NoSuchFieldException e) {
     if (clazz.getSuperclass() != null) {
       return getFieldFromBean(clazz.getSuperclass(), fieldName, originalClass);
     }
     throw new MappingException(
         "No such field found " + originalClass.getName() + "." + fieldName, e);
   }
 }
 public static Field makeAccessible(Class<?> target, String fieldName) {
   try {
     final Field field = target.getDeclaredField(fieldName);
     return (Field)
         AccessController.doPrivileged(
             new PrivilegedExceptionAction<Object>() {
               public Object run() throws IllegalAccessException, InvocationTargetException {
                 if (!field.isAccessible()) field.setAccessible(true);
                 return field;
               }
             });
   } catch (NoSuchFieldException | PrivilegedActionException e) {
     System.out.print("");
   } // keep quiet IError.printStackTrace(e); }
   return null;
 }
示例#13
0
 /**
  * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
  *
  * <p>如向上转型到Object仍无法找到, 返回null.
  */
 public static Field getAccessibleField(final Object obj, final String fieldName) {
   //		AssertUtil.notNull(obj, "object不能为空");
   //		AssertUtil.hasText(fieldName, "fieldName");
   for (Class<?> superClass = obj.getClass();
       superClass != Object.class;
       superClass = superClass.getSuperclass()) {
     try {
       Field field = superClass.getDeclaredField(fieldName);
       field.setAccessible(true);
       return field;
     } catch (NoSuchFieldException e) { // NOSONAR
       // Field不在当前类定义,继续向上转型
     }
   }
   return null;
 }
示例#14
0
 /**
  * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
  *
  * <p>如向上转型到Object仍无法找到, 返回null.
  */
 public static Field getAccessibleField(final Object obj, final String fieldName) {
   Validate.notNull(obj, "object can't be null");
   Validate.notBlank(fieldName, "fieldName can't be blank");
   for (Class<?> superClass = obj.getClass();
       superClass != Object.class;
       superClass = superClass.getSuperclass()) {
     try {
       Field field = superClass.getDeclaredField(fieldName);
       makeAccessible(field);
       return field;
     } catch (NoSuchFieldException e) { // NOSONAR
       // Field不在当前类定义,继续向上转型
       continue; // new add
     }
   }
   return null;
 }
    LockedUpdater(Class<T> tclass, String fieldName, Class<?> caller) {
      Field field = null;
      int modifiers = 0;
      try {
        field = tclass.getDeclaredField(fieldName);
        modifiers = field.getModifiers();
        sun.reflect.misc.ReflectUtil.ensureMemberAccess(caller, tclass, null, modifiers);
        sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }

      Class fieldt = field.getType();
      if (fieldt != long.class) throw new IllegalArgumentException("Must be long type");

      if (!Modifier.isVolatile(modifiers))
        throw new IllegalArgumentException("Must be volatile type");

      this.cclass = (Modifier.isProtected(modifiers) && caller != tclass) ? caller : null;
      this.tclass = tclass;
      offset = unsafe.objectFieldOffset(field);
    }
  /** Initialize constants and try to collect information about the JVM internals. */
  static {
    // Initialize empirically measured defaults. We'll modify them to the current
    // JVM settings later on if possible.
    int referenceSize = Constants.JRE_IS_64BIT ? 8 : 4;
    int objectHeader = Constants.JRE_IS_64BIT ? 16 : 8;
    // The following is objectHeader + NUM_BYTES_INT, but aligned (object alignment)
    // so on 64 bit JVMs it'll be align(16 + 4, @8) = 24.
    int arrayHeader = Constants.JRE_IS_64BIT ? 24 : 12;

    supportedFeatures = EnumSet.noneOf(JvmFeature.class);

    Class<?> unsafeClass = null;
    Object tempTheUnsafe = null;
    try {
      unsafeClass = Class.forName("sun.misc.Unsafe");
      final Field unsafeField = unsafeClass.getDeclaredField("theUnsafe");
      unsafeField.setAccessible(true);
      tempTheUnsafe = unsafeField.get(null);
    } catch (Exception e) {
      // Ignore.
    }
    theUnsafe = tempTheUnsafe;

    // get object reference size by getting scale factor of Object[] arrays:
    try {
      final Method arrayIndexScaleM = unsafeClass.getMethod("arrayIndexScale", Class.class);
      referenceSize = ((Number) arrayIndexScaleM.invoke(theUnsafe, Object[].class)).intValue();
      supportedFeatures.add(JvmFeature.OBJECT_REFERENCE_SIZE);
    } catch (Exception e) {
      // ignore.
    }

    // "best guess" based on reference size. We will attempt to modify
    // these to exact values if there is supported infrastructure.
    objectHeader = Constants.JRE_IS_64BIT ? (8 + referenceSize) : 8;
    arrayHeader = Constants.JRE_IS_64BIT ? (8 + 2 * referenceSize) : 12;

    // get the object header size:
    // - first try out if the field offsets are not scaled (see warning in Unsafe docs)
    // - get the object header size by getting the field offset of the first field of a dummy object
    // If the scaling is byte-wise and unsafe is available, enable dynamic size measurement for
    // estimateRamUsage().
    Method tempObjectFieldOffsetMethod = null;
    try {
      final Method objectFieldOffsetM = unsafeClass.getMethod("objectFieldOffset", Field.class);
      final Field dummy1Field = DummyTwoLongObject.class.getDeclaredField("dummy1");
      final int ofs1 = ((Number) objectFieldOffsetM.invoke(theUnsafe, dummy1Field)).intValue();
      final Field dummy2Field = DummyTwoLongObject.class.getDeclaredField("dummy2");
      final int ofs2 = ((Number) objectFieldOffsetM.invoke(theUnsafe, dummy2Field)).intValue();
      if (Math.abs(ofs2 - ofs1) == NUM_BYTES_LONG) {
        final Field baseField = DummyOneFieldObject.class.getDeclaredField("base");
        objectHeader = ((Number) objectFieldOffsetM.invoke(theUnsafe, baseField)).intValue();
        supportedFeatures.add(JvmFeature.FIELD_OFFSETS);
        tempObjectFieldOffsetMethod = objectFieldOffsetM;
      }
    } catch (Exception e) {
      // Ignore.
    }
    objectFieldOffsetMethod = tempObjectFieldOffsetMethod;

    // Get the array header size by retrieving the array base offset
    // (offset of the first element of an array).
    try {
      final Method arrayBaseOffsetM = unsafeClass.getMethod("arrayBaseOffset", Class.class);
      // we calculate that only for byte[] arrays, it's actually the same for all types:
      arrayHeader = ((Number) arrayBaseOffsetM.invoke(theUnsafe, byte[].class)).intValue();
      supportedFeatures.add(JvmFeature.ARRAY_HEADER_SIZE);
    } catch (Exception e) {
      // Ignore.
    }

    NUM_BYTES_OBJECT_REF = referenceSize;
    NUM_BYTES_OBJECT_HEADER = objectHeader;
    NUM_BYTES_ARRAY_HEADER = arrayHeader;

    // Try to get the object alignment (the default seems to be 8 on Hotspot,
    // regardless of the architecture).
    int objectAlignment = 8;
    try {
      final Class<?> beanClazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean");
      // Try to get the diagnostic mxbean without calling {@link
      // ManagementFactory#getPlatformMBeanServer()}
      // which starts AWT thread (and shows junk in the dock) on a Mac:
      Object hotSpotBean;
      // Java 7+, HotSpot
      try {
        hotSpotBean =
            ManagementFactory.class
                .getMethod("getPlatformMXBean", Class.class)
                .invoke(null, beanClazz);
      } catch (Exception e1) {
        // Java 6, HotSpot
        try {
          Class<?> sunMF = Class.forName("sun.management.ManagementFactory");
          hotSpotBean = sunMF.getMethod("getDiagnosticMXBean").invoke(null);
        } catch (Exception e2) {
          // Last resort option is an attempt to get it from ManagementFactory's server anyway (may
          // start AWT).
          hotSpotBean =
              ManagementFactory.newPlatformMXBeanProxy(
                  ManagementFactory.getPlatformMBeanServer(),
                  "com.sun.management:type=HotSpotDiagnostic",
                  beanClazz);
        }
      }
      if (hotSpotBean != null) {
        final Method getVMOptionMethod = beanClazz.getMethod("getVMOption", String.class);
        final Object vmOption = getVMOptionMethod.invoke(hotSpotBean, "ObjectAlignmentInBytes");
        objectAlignment =
            Integer.parseInt(vmOption.getClass().getMethod("getValue").invoke(vmOption).toString());
        supportedFeatures.add(JvmFeature.OBJECT_ALIGNMENT);
      }
    } catch (Exception e) {
      // Ignore.
    }

    NUM_BYTES_OBJECT_ALIGNMENT = objectAlignment;

    JVM_INFO_STRING =
        "[JVM: "
            + Constants.JVM_NAME
            + ", "
            + Constants.JVM_VERSION
            + ", "
            + Constants.JVM_VENDOR
            + ", "
            + Constants.JAVA_VENDOR
            + ", "
            + Constants.JAVA_VERSION
            + "]";
  }
示例#17
0
  public Type navigateQualified(String name, Type[] qualifiers) throws OclTypeException {
    Type theQualifier = null;

    if (qualifiers != null) {
      if (qualifiers.length == 1) theQualifier = qualifiers[0];
      else throw new OclTypeException("ReflectionFacade can handle one qualifier only");
    }
    // System.out.println("ClassAny.navigateQualified:"+this+" "+name);
    Type ret = Basic.navigateAnyQualified(name, this, qualifiers);
    if (ret != null) return ret;
    String[] javaNames = rf.nameAdapter.getNames(name);
    Field f = null;
    for (int i = 0; i < javaNames.length && f == null; i++) {
      Class nextClass = c;
      while (nextClass != null && f == null) {
        try {
          f = nextClass.getDeclaredField(javaNames[i]);
        } catch (NoSuchFieldException nsf) {
          // try next class
        }
        nextClass = nextClass.getSuperclass();
      }
    }
    if (f == null) {
      throw new OclTypeException(c.getName() + " has no field " + name);
    }
    Class type = f.getType();
    Type modeltype = getTypeForClass(type);

    if (modeltype instanceof Collection) {
      Class elementtype = rf.getElementType(f);

      if (rf.reflAdapter.isMap(type)) {
        if (theQualifier == null) {
          if (elementtype != null)
            return new Collection(
                ((Collection) modeltype).getCollectionKind(), getTypeForClass(elementtype));
          else return modeltype;
        } else {
          Class keytype_class = rf.getKeyType(f);
          Type keytype = null;
          if (keytype_class != null) keytype = getTypeForClass(keytype_class);

          if (keytype != null) {
            if (!theQualifier.equals(keytype))
              throw new OclTypeException(
                  "feature "
                      + name
                      + " in classifier "
                      + c
                      + ": expected qualifier type "
                      + keytype
                      + " found "
                      + theQualifier
                      + ".");
            if (elementtype != null) return getTypeForClass(elementtype);
            else
              throw new OclTypeException(
                  "feature "
                      + name
                      + "["
                      + keytype
                      + "] in classifier "
                      + c
                      + " has no @element-type tag.");
          } else
            throw new OclTypeException(
                "feature "
                    + name
                    + " in classifier "
                    + c
                    + ": qualified with type "
                    + theQualifier
                    + ", but feature has no @keytype tag.");
        }
      } else {
        if (theQualifier != null)
          throw new OclTypeException(
              "feature " + name + " in classifier " + c + " cannot be qualified.");

        if (elementtype != null)
          return new Collection(
              ((Collection) modeltype).getCollectionKind(), getTypeForClass(elementtype));
        else return modeltype;
      }
    } else {
      if (theQualifier != null)
        throw new OclTypeException(
            "feature " + name + " in classifier " + c + " cannot be qualified.");
      return modeltype;
    }
  }
示例#18
0
 public static Object getAdapterSelf(Class<?> adapterClass, Object adapter)
     throws NoSuchFieldException, IllegalAccessException {
   Field self = adapterClass.getDeclaredField("self");
   return self.get(adapter);
 }