Exemple #1
0
 /**
  * Returns a Field object that represents an attribute of a class
  *
  * @param type the class that holds the attribute
  * @param name the name of the attribute
  * @return a Field object that represents the attribute
  */
 public static Field getField(Class<?> type, String name) {
   try {
     return type.getField(name);
   } catch (NoSuchFieldException e) {
     throw ExceptionMapper.configurationException(e, type.getName() + '.' + name);
   }
 }
Exemple #2
0
  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();
  }
Exemple #3
0
 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;
   }
 }
Exemple #4
0
 // 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;
 }
  public static Object invoke_description(Class c) {
    try {
      Field f = c.getField("description_array");
      return f.get(null);
    } catch (NoSuchFieldException e) {
    } // eat the exception; apparently c is not a helper
    catch (Exception e) {
    } // HMM, SHOULD WE TRY HARDER TO FIGURE OUT WHAT'S GOING ON HERE ???

    return null;
  }
Exemple #6
0
  int[] init(int... dimensions) {
    int size = dimensions.length > 0 ? dimensions[0] : 0;
    if (___subrecord___ == null) {
      final String[] indexPrefixes = {
        "", "s", "_", "Index", "Length", "Ref", "Header", "Info", "Table"
      };
      for (String indexPrefix : indexPrefixes) {
        try {
          ___subrecord___ =
              (Class<? extends Enum>)
                  Class.forName(getClass().getPackage().getName() + '.' + name() + indexPrefix);
          try {
            size = ___subrecord___.getField("___recordlen___").getInt(null);
          } catch (Exception e) {
          }
          break;
        } catch (ClassNotFoundException e) {
        }
      }
    }

    for (String vPrefixe1 :
        new String[] {
          "_", "", "$", "Value",
        }) {
      if (___valueclass___ != null) break;
      String suffix = vPrefixe1;
      for (String name1 :
          new String[] {
            name().toLowerCase(), name(),
          }) {
        if (___valueclass___ != null) break;
        final String trailName = name1;
        if (trailName.endsWith(suffix)) {
          for (String aPackage1 :
              new String[] {
                "", getClass().getPackage().getName() + ".", "java.lang.", "java.util.",
              })
            if (___valueclass___ == null) break;
            else
              try {
                ___valueclass___ = Class.forName(aPackage1 + name().replace(suffix, ""));
              } catch (ClassNotFoundException e) {
              }
        }
      }
    }

    int seek = dimensions.length > 1 ? dimensions[1] : ___recordlen___;
    ___recordlen___ = Math.max(___recordlen___, seek + size);
    return new int[] {size, seek};
  }
Exemple #7
0
 public static Object getFieldValue(Object target, String name, boolean strict) {
   Class<?> type = target.getClass();
   try {
     Field field = type.getField(name);
     return getFieldValue(field, target, strict);
   } catch (NoSuchFieldException e) {
     if (strict) throw ExceptionMapper.configurationException(e, type.getName() + '.' + name);
     else {
       escalator.escalate("Class '" + type + "' does not have a field '" + name + "'", type, name);
       return null;
     }
   }
 }
    /**
     * Initializes the fields of this class based on the first two lines of a case which include the
     * class name and parameter types.
     *
     * @return true is end of file is reached.
     */
    private static boolean initFields(LineNumberReader commands, boolean generatingCommands) {

      results = new StringBuffer();

      String className = getNextRealLine(commands);

      // End of file reached
      if (className == null) return true;

      // Load the class from file
      Class<? extends Invariant> classToTest = asInvClass(getClass(className));

      try {
        classToTest.getField("dkconfig_enabled"); // Enable if needs to be done
        InvariantAddAndCheckTester.config.apply(className + ".enabled", "true");
      } catch (NoSuchFieldException e) { // Otherwise do nothing
      }

      if (generatingCommands) {
        results.append(className + lineSep);
      }

      // Instantiate variables to be used as the names in the
      // invariants, variables are labeled a,b,c and so on as they
      // appear
      String typeString = getNextRealLine(commands);

      types = getTypes(typeString);

      VarInfo[] vars = getVarInfos(classToTest, types);
      PptSlice sl = createSlice(vars, daikon.test.Common.makePptTopLevel("Test:::OBJECT", vars));

      // Create an actual instance of the class
      invariantToTest = instantiateClass(classToTest, sl);

      addModified = getAddModified(invariantToTest.getClass());
      checkModified = getCheckModified(invariantToTest.getClass());
      outputProducer = getOutputProducer(invariantToTest.getClass());

      assert getArity(invariantToTest.getClass()) == types.length;

      if (generatingCommands) {
        results.append(typeString + lineSep);
      }
      return false;
    }
 static {
   ParticleUtils.version = "";
   try {
     ParticleUtils.version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
     ParticleUtils.packetType = Class.forName(getPacketPlayOutParticles());
     final Class<?> typeCraftPlayer = Class.forName(getCraftPlayerClasspath());
     final Class<?> typeNMSPlayer = Class.forName(getNMSPlayerClasspath());
     final Class<?> typePlayerConnection = Class.forName(getPlayerConnectionClasspath());
     ParticleUtils.getHandle = typeCraftPlayer.getMethod("getHandle", (Class<?>[]) new Class[0]);
     ParticleUtils.playerConnection = typeNMSPlayer.getField("playerConnection");
     ParticleUtils.sendPacket =
         typePlayerConnection.getMethod("sendPacket", Class.forName(getPacketClasspath()));
   } catch (Exception e) {
     System.out.println("Failed to setup reflection for PacketPlayOutWorldParticles");
     e.printStackTrace();
   }
 }
Exemple #10
0
  public static void main(String[] args)
      throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
          InvocationTargetException, NoSuchFieldException {
    Reflection obj = new Reflection();
    Class<Reflection> c = Reflection.class;

    // test the ability to reflectively get constants, which are usually baked
    // in to bytecodes by the compiler
    Field f = c.getField("constValue");
    System.out.println(f.get(null));
    Field f2 = c.getField("constInt");
    System.out.println(f2.get(null));
    Field f3 = c.getField("constFloat");
    System.out.println(f3.get(null));
    Field f4 = c.getField("constDouble");
    System.out.println(f4.get(null));
    Field f5 = c.getField("constLong");
    System.out.println(f5.get(null));
    Field f6 = c.getField("constShort");
    System.out.println(f6.get(null));
    Field f7 = c.getField("constBool");
    System.out.println(f7.get(null));

    Method bytecodeMethod = c.getClass().getMethod("toString");
    Method nativeMethod = c.getClass().getMethod("isArray");
    Method nativeMethodWithArgs = c.getClass().getMethod("isInstance", Object.class);
    Method unboxingMethod = c.getMethod("add", long.class, long.class);
    Method boxingMethod = c.getMethod("add", Long.class, Long.class);
    Method voidMethod = c.getMethod("foo");
    // regular method reflected invocation
    System.out.println("toString: " + bytecodeMethod.invoke(c));
    // native method reflected invocation
    System.out.println("is array? " + nativeMethod.invoke(c));
    // native method reflected invocation with parameters
    System.out.println("is instance? " + nativeMethodWithArgs.invoke(c, obj));
    // unboxing has to be handled specially by our native method invoker
    Long a = new Long(40L);
    Long b = new Long(2L);
    System.out.println("unboxing: " + unboxingMethod.invoke(null, a, b));
    // boxing is handled by javac
    System.out.println("boxing: " + boxingMethod.invoke(null, 1300L, 37L));
    // void return values
    System.out.println("void return: " + voidMethod.invoke(null));
  }
Exemple #11
0
  public Predicted(DataFrame<M> f, String pfn) {
    frame = f;
    numericField = null;

    Class<M> mcls = frame.getModelClass();

    try {
      Field mf = mcls.getField(pfn);
      Class t = mf.getType();
      if (Model.isSubclass(t, Number.class)) {
        numericField = mf;
      } else {
        throw new IllegalArgumentException(
            String.format("Field %s is not numeric", pfn, t.getName()));
      }

    } catch (NoSuchFieldException e) {
      e.printStackTrace();
      throw new IllegalArgumentException(String.format("Unknown field name: %s", pfn));
    }
  }
Exemple #12
0
  // Needed by NativeJavaObject serializer
  public static void writeAdapterObject(Object javaObject, ObjectOutputStream out)
      throws IOException {
    Class<?> cl = javaObject.getClass();
    out.writeObject(cl.getSuperclass().getName());

    Class<?>[] interfaces = cl.getInterfaces();
    String[] interfaceNames = new String[interfaces.length];

    for (int i = 0; i < interfaces.length; i++) interfaceNames[i] = interfaces[i].getName();

    out.writeObject(interfaceNames);

    try {
      Object delegee = cl.getField("delegee").get(javaObject);
      out.writeObject(delegee);
      return;
    } catch (IllegalAccessException e) {
    } catch (NoSuchFieldException e) {
    }
    throw new IOException();
  }
Exemple #13
0
  public static void getParam(vectTableModel _model) {

    String xline;
    StringTokenizer st = null;
    String s1 = null;
    String s2 = null;
    Object m1 = null;
    Field fx = null;
    int j = 0;

    try {
      Class c = Class.forName("jneat.Neat");
      Field[] fieldlist = c.getDeclaredFields();

      int number_params = fieldlist.length / 2;

      j = 0;
      for (int i = 0; i < number_params; i++) {
        Field f1 = fieldlist[i];
        String nomeF = f1.getName();
        String nomeF1 = nomeF.substring(2);
        if (nomeF.substring(0, 2).equalsIgnoreCase("p_")) {
          Object o1 = nomeF1;
          fx = c.getField("p_" + nomeF1);
          Object o2 = fx.get(c);

          _model.setValueAt(o1, j, 0);
          _model.setValueAt(o2, j, 1);

          j++;
        }
      }

    } catch (Throwable e) {
      System.err.println(e);
    }

    _model.rows = j;
    return;
  }
Exemple #14
0
 static {
   // compute primitives/primitiveMap/primitiveToWrapper
   for (Class<?> c : primitiveWrappers) {
     try {
       Field f = c.getField("TYPE");
       Class<?> p = (Class<?>) f.get(null);
       primitives.add(p);
       primitiveMap.put(p.getName(), p);
       primitiveToWrapper.put(p.getName(), c);
     } catch (Exception e) {
       throw new AssertionError(e);
     }
   }
   // compute editableTypes
   for (Class<?> c : primitives) {
     editableTypes.add(c.getName());
   }
   for (Class<?> c : primitiveWrappers) {
     editableTypes.add(c.getName());
   }
   for (Class<?> c : extraEditableClasses) {
     editableTypes.add(c.getName());
   }
   // compute numericalTypes
   for (Class<?> c : primitives) {
     String name = c.getName();
     if (!name.equals(Boolean.TYPE.getName())) {
       numericalTypes.add(name);
     }
   }
   for (Class<?> c : primitiveWrappers) {
     String name = c.getName();
     if (!name.equals(Boolean.class.getName())) {
       numericalTypes.add(name);
     }
   }
 }
Exemple #15
0
  public static void updateParam(vectTableModel _model) {
    //
    // write to file xpar all parameters.....
    //

    for (int j = 0; j < _model.data.size(); j++) {
      try {
        Class c = Class.forName("jneat.Neat");
        ParamValue ox = (ParamValue) _model.data.elementAt(j);

        Object k = _model.getValueAt(j, 0);
        Object kv = _model.getValueAt(j, 1);

        String xkey = k.toString();
        String xval = kv.toString();
        /*
        System.out.print("\n j = "+j+" xkey = "+xkey);
        System.out.print(" xval = "+xval);
        */
        Field f1 = c.getField("p_" + xkey);
        Object fty = f1.getType();

        if (fty.toString().equals("double")) {
          double n1 = Double.parseDouble(xval);
          f1.set(c, (new Double(n1)));
        }
        if (fty.toString().equals("int")) {
          int n1 = Integer.parseInt(xval);
          f1.set(c, (new Integer(n1)));
        }

      } catch (Throwable e) {
        System.out.print("\n errore su jneat.updateParam = " + e);
      }
    }
  }
  public static void main(String[] args) {

    // Obtain the class object if we know the name of the class
    Class rental = RentCar.class;
    try {
      // get the absolute name of the class
      String rentalClassPackage = rental.getName();
      System.out.println("Class Name is: " + rentalClassPackage);

      // get the simple name of the class (without package info)
      String rentalClassNoPackage = rental.getSimpleName();
      System.out.println("Class Name without package is: " + rentalClassNoPackage);

      // get the package name of the class
      Package rentalPackage = rental.getPackage();
      System.out.println("Package Name is: " + rentalPackage);

      // get all the constructors of the class
      Constructor[] constructors = rental.getConstructors();
      System.out.println("Constructors are: " + Arrays.toString(constructors));

      // get constructor with specific argument
      Constructor constructor = rental.getConstructor(Integer.TYPE);

      // initializing an object of the RentCar class
      RentCar rent = (RentCar) constructor.newInstance(455);

      // get all methods of the class including declared methods of
      // superclasses
      // in that case, superclass of RentCar is the class java.lang.Object
      Method[] allmethods = rental.getMethods();
      System.out.println("Methods are: " + Arrays.toString(allmethods));
      for (Method method : allmethods) {
        System.out.println("method = " + method.getName());
      }

      // get all methods declared in the class
      // but excludes inherited methods.
      Method[] declaredMethods = rental.getDeclaredMethods();
      System.out.println("Declared Methods are: " + Arrays.toString(declaredMethods));
      for (Method dmethod : declaredMethods) {
        System.out.println("method = " + dmethod.getName());
      }

      // get method with specific name and parameters
      Method oneMethod = rental.getMethod("computeRentalCost", new Class[] {Integer.TYPE});
      System.out.println("Method is: " + oneMethod);

      // call computeRentalCost method with parameter int
      oneMethod.invoke(rent, 4);

      // get all the parameters of computeRentalCost
      Class[] parameterTypes = oneMethod.getParameterTypes();
      System.out.println(
          "Parameter types of computeRentalCost() are: " + Arrays.toString(parameterTypes));

      // get the return type of computeRentalCost
      Class returnType = oneMethod.getReturnType();
      System.out.println("Return type is: " + returnType);

      // gets all the public member fields of the class RentCar
      Field[] fields = rental.getFields();

      System.out.println("Public Fields are: ");
      for (Field oneField : fields) {
        // get public field name
        Field field = rental.getField(oneField.getName());
        String fieldname = field.getName();
        System.out.println("Fieldname is: " + fieldname);

        // get public field type
        Object fieldType = field.getType();
        System.out.println("Type of field " + fieldname + " is: " + fieldType);

        // get public field value
        Object value = field.get(rent);
        System.out.println("Value of field " + fieldname + " is: " + value);
      }

      // How to access private member fields of the class

      // getDeclaredField() returns the private field
      Field privateField = RentCar.class.getDeclaredField("type");

      String name = privateField.getName();
      System.out.println("One private Fieldname is: " + name);
      // makes this private field instance accessible
      // for reflection use only, not normal code
      privateField.setAccessible(true);

      // get the value of this private field
      String fieldValue = (String) privateField.get(rent);
      System.out.println("fieldValue = " + fieldValue);

    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }