protected PsmMethodAction(Class c, String m, Class[] argArray) {
    // This prevents IllegalAccessExceptions when attempting to
    // invoke methods on a class that is in another package and not
    // defined 'public'.
    if (!Modifier.isPublic(c.getModifiers())) {
      throw new IllegalPsmMethodActionException("Action class must be public.");
    }

    try {
      method = c.getMethod(m, argArray);
    } catch (NoSuchMethodException ex) {
      throw new IllegalPsmMethodActionException(ex.toString() + ": method " + m);
    }

    // Check each exception this method declares thrown.  If it declares
    // exceptions, and any of them are not runtime exceptions, abort.
    Class[] exceptionTypes = method.getExceptionTypes();
    for (int i = 0; i < exceptionTypes.length; i++) {
      Class exceptionClass = exceptionTypes[i];
      if (!RuntimeException.class.isAssignableFrom(exceptionClass)) {
        throw new IllegalPsmMethodActionException(
            "Method must not declare non-Runtime " + "exceptions.");
      }
    }

    // Ensure that the method returns PsmEvent
    if (PsmEvent.class != method.getReturnType()) {
      throw new IllegalPsmMethodActionException("Method return type must be PsmEvent");
    }

    // Ensure that both the method is both public and static.
    if (!Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) {
      throw new IllegalPsmMethodActionException("Method " + m + " must be static and public.");
    }
  }
Beispiel #2
0
  public static void invokeSetMethod(Object obj, String prop, String value)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Class cl = obj.getClass();
    // change first letter to uppercase
    String setMeth = "set" + prop.substring(0, 1).toUpperCase() + prop.substring(1);

    // try string method
    try {
      Class[] cldef = {String.class};
      Method meth = cl.getMethod(setMeth, cldef);
      Object[] params = {value};
      meth.invoke(obj, params);
      return;
    } catch (NoSuchMethodException ex) {
      try {
        // try int method
        Class[] cldef = {Integer.TYPE};
        Method meth = cl.getMethod(setMeth, cldef);
        Object[] params = {Integer.valueOf(value)};
        meth.invoke(obj, params);
        return;
      } catch (NoSuchMethodException nsmex) {
        // try boolean method
        Class[] cldef = {Boolean.TYPE};
        Method meth = cl.getMethod(setMeth, cldef);
        Object[] params = {Boolean.valueOf(value)};
        meth.invoke(obj, params);
        return;
      }
    }
  }
Beispiel #3
0
  void enableLionFS() {
    try {
      String version = System.getProperty("os.version");
      String[] tokens = version.split("\\.");
      int major = Integer.parseInt(tokens[0]), minor = 0;
      if (tokens.length > 1) minor = Integer.parseInt(tokens[1]);
      if (major < 10 || (major == 10 && minor < 7))
        throw new Exception("Operating system version is " + version);

      Class fsuClass = Class.forName("com.apple.eawt.FullScreenUtilities");
      Class argClasses[] = new Class[] {Window.class, Boolean.TYPE};
      Method setWindowCanFullScreen = fsuClass.getMethod("setWindowCanFullScreen", argClasses);
      setWindowCanFullScreen.invoke(fsuClass, this, true);

      Class fsListenerClass = Class.forName("com.apple.eawt.FullScreenListener");
      InvocationHandler fsHandler = new MyInvocationHandler(cc);
      Object proxy =
          Proxy.newProxyInstance(
              fsListenerClass.getClassLoader(), new Class[] {fsListenerClass}, fsHandler);
      argClasses = new Class[] {Window.class, fsListenerClass};
      Method addFullScreenListenerTo = fsuClass.getMethod("addFullScreenListenerTo", argClasses);
      addFullScreenListenerTo.invoke(fsuClass, this, proxy);

      canDoLionFS = true;
    } catch (Exception e) {
      vlog.debug("Could not enable OS X 10.7+ full-screen mode:");
      vlog.debug("  " + e.toString());
    }
  }
 Document parseDocument(String filename) throws Exception {
   FileReader reader = new FileReader(filename);
   String firstLine = new BufferedReader(reader).readLine();
   reader.close();
   Document document = null;
   if (firstLine.startsWith("<?xml")) {
     System.err.println("XML detected; using default XML parser.");
   } else {
     try {
       Class nekoParserClass = Class.forName("org.cyberneko.html.parsers.DOMParser");
       Object parser = nekoParserClass.newInstance();
       Method parse = nekoParserClass.getMethod("parse", new Class[] {String.class});
       Method getDocument = nekoParserClass.getMethod("getDocument", new Class[0]);
       parse.invoke(parser, filename);
       document = (Document) getDocument.invoke(parser);
     } catch (Exception e) {
       System.err.println("NekoHTML HTML parser not found; HTML4 support disabled.");
     }
   }
   if (document == null) {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     try { // http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic
       factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     } catch (ParserConfigurationException e) {
       System.err.println("Warning: Could not disable external DTD loading");
     }
     DocumentBuilder builder = factory.newDocumentBuilder();
     document = builder.parse(filename);
   }
   return document;
 }
Beispiel #5
0
  /** Do the execution. */
  public void execute() throws BuildException {
    Method setProjectM = null;
    try {
      Class c = proxy.getClass();
      setProjectM = c.getMethod("setProject", new Class[] {Project.class});
      if (setProjectM != null) {
        setProjectM.invoke(proxy, new Object[] {project});
      }
    } catch (Exception ex) {
      log("Error setting project in " + proxy.getClass(), Project.MSG_ERR);
      throw new BuildException(ex);
    }

    Method executeM = null;
    try {
      Class c = proxy.getClass();
      executeM = c.getMethod("execute", new Class[0]);
      if (executeM == null) {
        log("No execute in " + proxy.getClass(), Project.MSG_ERR);
        throw new BuildException("No execute in " + proxy.getClass());
      }
      executeM.invoke(proxy, null);
      return;
    } catch (Exception ex) {
      log("Error in " + proxy.getClass(), Project.MSG_ERR);
      throw new BuildException(ex);
    }
  }
    private static Optional<Method> lookup(
        Class<?> sourceClass, String methodName, Class<?>[] parameterTypes) {
      Method match;
      try {
        match = sourceClass.getMethod(methodName, parameterTypes);
      } catch (NoSuchMethodException e) {
        return Optional.absent();
      }

      LinkedList<Class<?>> queue = new LinkedList<Class<?>>();
      queue.add(sourceClass);
      while (!queue.isEmpty()) {
        Class<?> c = queue.removeFirst();
        try {
          match = c.getMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException e) {
          // ignore
        }
        for (Class<?> interfaceType : c.getInterfaces()) {
          queue.addFirst(interfaceType);
        }
        if (c.getSuperclass() != null) {
          queue.addFirst(c.getSuperclass());
        }
      }
      match.setAccessible(true);
      return Optional.of(match);
    }
  /** private method which actually will do all of our work for the sample */
  private void executeSample() {

    String query = "select anEmployee from staff2";
    try {
      Statement stmt = _con.createStatement();
      ;

      // Execute the query which will return an Employee object
      // We will cast this using the Person interface. Note the
      // Person interface class MUST be in your CLASSPATH. You
      // Do not need Employee in your CLASSPATH.
      ResultSet rs = stmt.executeQuery(query);

      output("***Using interface class\n");
      while (rs.next()) {
        Person aPerson = (Person) rs.getObject(1);
        displayMethods(aPerson.getClass());
        output(
            "The person is: "
                + aPerson.toString()
                + "\nFirst Name= "
                + aPerson.getFirstName()
                + "\nLast Name= "
                + aPerson.getLastName()
                + "\n");
      }
      // Now execute the same query, but this time we will use
      // reflection to access the class.  Again, only the interface
      // Person is required in the CLASSPATH
      rs = stmt.executeQuery(query);

      output("***Using reflection\n");
      Object theObj = null;
      while (rs.next()) {
        theObj = rs.getObject(1);
        output("The person is: " + theObj.toString() + "\n");
        Class theClass = theObj.getClass();
        displayMethods(theClass);
        Method m1 = theClass.getMethod("toString", new Class[0]);
        Method m2 = theClass.getMethod("getFirstName", new Class[0]);
        Method m3 = theClass.getMethod("getLastName", new Class[0]);
        output(
            "The person is: "
                + (Object) m1.invoke(theObj, new Object[0])
                + "\nFirst Name= "
                + (Object) m2.invoke(theObj, new Object[0])
                + "\nLast Name= "
                + (Object) m3.invoke(theObj, new Object[0])
                + "\n");
      }
      rs.close();
      stmt.close();
    } catch (SQLException sqe) {
      displaySQLEx(sqe);
    } catch (Exception e) {
      error("Unexpected exception : " + e.toString() + "\n");
      e.printStackTrace();
    }
  }
Beispiel #8
0
 public void toggleLionFS() {
   try {
     Class appClass = Class.forName("com.apple.eawt.Application");
     Method getApplication = appClass.getMethod("getApplication", (Class[]) null);
     Object app = getApplication.invoke(appClass);
     Method requestToggleFullScreen = appClass.getMethod("requestToggleFullScreen", Window.class);
     requestToggleFullScreen.invoke(app, this);
   } catch (Exception e) {
     vlog.debug("Could not toggle OS X 10.7+ full-screen mode:");
     vlog.debug("  " + e.toString());
   }
 }
Beispiel #9
0
  /**
   * This creates a new <code>{@link Document}</code> from an existing <code>InputStream</code> by
   * letting a DOM parser handle parsing using the supplied stream.
   *
   * @param in <code>InputStream</code> to parse.
   * @param validate <code>boolean</code> to indicate if validation should occur.
   * @return <code>Document</code> - instance ready for use.
   * @throws IOException when I/O error occurs.
   * @throws JDOMException when errors occur in parsing.
   */
  public Document getDocument(InputStream in, boolean validate) throws IOException, JDOMException {

    try {
      // Load the parser class
      Class parserClass = Class.forName("org.apache.xerces.parsers.DOMParser");
      Object parser = parserClass.newInstance();

      // Set validation
      Method setFeature =
          parserClass.getMethod("setFeature", new Class[] {java.lang.String.class, boolean.class});
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/validation", new Boolean(validate)});

      // Set namespaces true
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/namespaces", new Boolean(true)});

      // Set the error handler
      if (validate) {
        Method setErrorHandler =
            parserClass.getMethod("setErrorHandler", new Class[] {ErrorHandler.class});
        setErrorHandler.invoke(parser, new Object[] {new BuilderErrorHandler()});
      }

      // Parse the document
      Method parse = parserClass.getMethod("parse", new Class[] {org.xml.sax.InputSource.class});
      parse.invoke(parser, new Object[] {new InputSource(in)});

      // Get the Document object
      Method getDocument = parserClass.getMethod("getDocument", null);
      Document doc = (Document) getDocument.invoke(parser, null);

      return doc;
    } catch (InvocationTargetException e) {
      Throwable targetException = e.getTargetException();
      if (targetException instanceof org.xml.sax.SAXParseException) {
        SAXParseException parseException = (SAXParseException) targetException;
        throw new JDOMException(
            "Error on line "
                + parseException.getLineNumber()
                + " of XML document: "
                + parseException.getMessage(),
            e);
      } else if (targetException instanceof IOException) {
        IOException ioException = (IOException) targetException;
        throw ioException;
      } else {
        throw new JDOMException(targetException.getMessage(), e);
      }
    } catch (Exception e) {
      throw new JDOMException(e.getClass().getName() + ": " + e.getMessage(), e);
    }
  }
 Method getWriteProperty(Method m, Class c) {
   try {
     if (m.getName().startsWith("get")) {
       return c.getMethod("set" + (m.getName().substring(3)), new Class[] {m.getReturnType()});
     } else if (m.getName().startsWith("is")) {
       return c.getMethod("set" + (m.getName().substring(2)), new Class[] {m.getReturnType()});
     } else return null;
   } catch (Exception e) // just in case of RuntimeExceptions
   {
     // couldn't find a setter
     return null;
   }
 }
 Method getName(Method m, Class c, boolean includeExtensions) {
   if (!includeExtensions) return null;
   try {
     if (m.getName().startsWith("get")) {
       return c.getMethod("name" + (m.getName().substring(3)), new Class[] {});
     } else if (m.getName().startsWith("is")) {
       return c.getMethod("name" + (m.getName().substring(2)), new Class[] {});
     } else return null;
   } catch (Exception e) // just in case of RuntimeExceptions
   {
     // couldn't find a domain
     return null;
   }
 }
 /* If it exists, returns a method of the form 'public boolean hideFoo() { ...}'.  In this method the developer can declare
 whether or not he wants to hide this property.  If there is no such method, we must assume that the property is to be
 shown. */
 Method getHidden(Method m, Class c, boolean includeExtensions) {
   if (!includeExtensions) return null;
   try {
     if (m.getName().startsWith("get")) {
       Method m2 = c.getMethod("hide" + (m.getName().substring(3)), new Class[] {});
       if (m2.getReturnType() == Boolean.TYPE) return m2;
     } else if (m.getName().startsWith("is")) {
       Method m2 = c.getMethod("hide" + (m.getName().substring(2)), new Class[] {});
       if (m2.getReturnType() == Boolean.TYPE) return m2;
     }
   } catch (Exception e) {
     // couldn't find a domain
   }
   return null;
 }
Beispiel #13
0
  public static void main(String[] args) throws Exception {
    Class classType = InvokeTester.class;
    Object invokeTester = classType.newInstance();

    // 调用InvokeTester对象的add()方法
    Method addMethod = classType.getMethod("add", new Class[] {int.class, int.class});
    Object result =
        addMethod.invoke(invokeTester, new Object[] {new Integer(100), new Integer(200)});
    System.out.println((Integer) result);

    // 调用InvokeTester对象的echo()方法
    Method echoMethod = classType.getMethod("echo", new Class[] {String.class});
    result = echoMethod.invoke(invokeTester, new Object[] {"Hello"});
    System.out.println((String) result);
  }
 /** Make a clone of the given object. */
 protected static Object makeClone(Object obj) {
   Object clone_obj = obj;
   if (obj instanceof String) {
     String string = (String) obj;
     clone_obj = (Object) new String(string);
   } else if (obj instanceof Integer) {
     clone_obj = new Integer(((Integer) obj).intValue());
   } else if (obj instanceof Float) {
     clone_obj = new Float(((Float) obj).floatValue());
   } else if (obj instanceof Double) {
     clone_obj = new Double(((Double) obj).doubleValue());
   } else if (obj instanceof Long) {
     clone_obj = new Long(((Long) obj).longValue());
   } else {
     // If a clone method exists for the object, then
     // invoke it
     try {
       Class cl = obj.getClass();
       Method meth = cl.getMethod("clone", null);
       clone_obj = meth.invoke(obj, null);
     } catch (SecurityException ex) {
       clone_obj = obj;
     } catch (IllegalArgumentException ex) {
       InternalErrorHandler.handleException(ex);
     } catch (IllegalAccessException ex) {
       clone_obj = obj;
     } catch (InvocationTargetException ex) {
       clone_obj = obj;
     } catch (NoSuchMethodException ex) {
       clone_obj = obj;
     }
   }
   return clone_obj;
 }
Beispiel #15
0
 /**
  * Gets the ObjectLoader for the specified class.
  *
  * @param classtype the class
  * @return the ObjectLoader
  */
 public static XML.ObjectLoader getLoader(Class classtype) {
   // look for registered loader first
   ObjectLoader loader = (ObjectLoader) loaders.get(classtype);
   // if no registered loader, look for static getLoader() method in class
   if (loader == null) {
     try {
       Method method = classtype.getMethod("getLoader", (Class[]) null); // $NON-NLS-1$
       if (method != null && Modifier.isStatic(method.getModifiers())) {
         loader = (ObjectLoader) method.invoke(null, (Object[]) null);
         if (loader != null) {
           // register loader for future calls
           setLoader(classtype, loader);
         }
       }
     } catch (Exception ex) {
       /** empty block */
     }
   }
   // if still no loader found, use the default loader
   if (loader == null) {
     if (defaultLoader == null) {
       defaultLoader = new XMLLoader();
     }
     loader = defaultLoader;
   }
   return loader;
 }
Beispiel #16
0
 /**
  * Insert the source code details, if available.
  *
  * @param ped The given program element.
  */
 public void addSourcePosition(ProgramElementDoc ped, int indent) {
   if (!addSrcInfo) return;
   if (JDiff.javaVersion.startsWith("1.1")
       || JDiff.javaVersion.startsWith("1.2")
       || JDiff.javaVersion.startsWith("1.3")) {
     return; // position() only appeared in J2SE1.4
   }
   try {
     // Could cache the method for improved performance
     Class c = ProgramElementDoc.class;
     Method m = c.getMethod("position", null);
     Object sp = m.invoke(ped, null);
     if (sp != null) {
       for (int i = 0; i < indent; i++) outputFile.print(" ");
       outputFile.println("src=\"" + sp + "\"");
     }
   } catch (NoSuchMethodException e2) {
     System.err.println("Error: method \"position\" not found");
     e2.printStackTrace();
   } catch (IllegalAccessException e4) {
     System.err.println("Error: class not permitted to be instantiated");
     e4.printStackTrace();
   } catch (InvocationTargetException e5) {
     System.err.println("Error: method \"position\" could not be invoked");
     e5.printStackTrace();
   } catch (Exception e6) {
     System.err.println("Error: ");
     e6.printStackTrace();
   }
 }
 /* gets target VM version from the given VMVersionMismatchException.
  * Note that we need to reflectively call the method because of we may
  * have got this from different classloader's namespace */
 private static String getVMVersion(Throwable throwable)
     throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
   // assert isVMVersionMismatch(throwable), "not a VMVersionMismatch"
   Class expClass = throwable.getClass();
   Method targetVersionMethod = expClass.getMethod("getTargetVersion", new Class[0]);
   return (String) targetVersionMethod.invoke(throwable);
 }
Beispiel #18
0
  private void callMethodForMultiPart(HttpServletRequest req, HttpServletResponse resp)
      throws Exception {
    String pinfo = req.getPathInfo();
    int pos = pinfo.indexOf('.');
    String cname = pinfo.substring(1, pos).replace('/', '.');
    String mname = pinfo.substring(pos + 1);

    MultiPartMap map = new MultiPartMap();
    FileItemIterator ite = new FileUpload().getItemIterator(req);
    while (ite.hasNext()) {
      FileItemStream item = ite.next();
      if (item.isFormField()) {
        map.put(item.getFieldName(), IOUtil.streamToString(item.openStream(), "UTF-8"));
      } else {
        FileItem val =
            new FileItem(
                item.getFileName(), item.getContentType(), IOUtil.streamToBytes(item.openStream()));
        map.put(item.getFieldName(), val);
      }
    }

    Class clazz = Class.forName(cname);
    Class[] types = new Class[] {MultiPartMap.class};
    Method method = clazz.getMethod(mname, types);
    if (method == null) {
      throw new RuntimeException("Not found method " + mname + "(Map)");
    }

    Object result = method.invoke(null, map);

    resp.setContentType(MIME_HTML + ";charset=utf-8");
    resp.getWriter().write(result.toString());
  }
Beispiel #19
0
  /**
   * Creates an <code>ComponentUI</code> implementation for the specified component. In other words
   * create the look and feel specific delegate object for <code>target</code>. This is done in two
   * steps:
   *
   * <ul>
   *   <li>Look up the name of the <code>ComponentUI</code> implementation class under the value
   *       returned by <code>target.getUIClassID()</code>.
   *   <li>Use the implementation classes static <code>createUI()</code> method to construct a look
   *       and feel delegate.
   * </ul>
   *
   * @param target the <code>JComponent</code> which needs a UI
   * @return the <code>ComponentUI</code> object
   */
  public ComponentUI getUI(JComponent target) {

    Object cl = get("ClassLoader");
    ClassLoader uiClassLoader =
        (cl != null) ? (ClassLoader) cl : target.getClass().getClassLoader();
    Class<? extends ComponentUI> uiClass = getUIClass(target.getUIClassID(), uiClassLoader);
    Object uiObject = null;

    if (uiClass == null) {
      getUIError("no ComponentUI class for: " + target);
    } else {
      try {
        Method m = (Method) get(uiClass);
        if (m == null) {
          m = uiClass.getMethod("createUI", new Class[] {JComponent.class});
          put(uiClass, m);
        }
        uiObject = MethodUtil.invoke(m, null, new Object[] {target});
      } catch (NoSuchMethodException e) {
        getUIError("static createUI() method not found in " + uiClass);
      } catch (Exception e) {
        getUIError("createUI() failed for " + target + " " + e);
      }
    }

    return (ComponentUI) uiObject;
  }
Beispiel #20
0
 Object createGuiElement(Class cls, EntityPlayer player, World world, int x, int y, int z) {
   try {
     try {
       if (debugGui)
         System.out.printf(
             "BaseMod.createGuiElement: Invoking create method of %s for %s in %s\n",
             cls, player, world);
       return cls.getMethod(
               "create", EntityPlayer.class, World.class, int.class, int.class, int.class)
           .invoke(null, player, world, x, y, z);
     } catch (NoSuchMethodException e) {
       if (debugGui)
         System.out.printf("BaseMod.createGuiElement: Invoking constructor of %s\n", cls);
       return cls.getConstructor(EntityPlayer.class, World.class, int.class, int.class, int.class)
           .newInstance(player, world, x, y, z);
     }
   } catch (Exception e) {
     Throwable cause = e.getCause();
     System.out.printf("BaseMod.createGuiElement: %s: %s\n", e, cause);
     if (cause != null) cause.printStackTrace();
     else e.printStackTrace();
     // throw new RuntimeException(e);
     return null;
   }
 }
  /**
   * Creates a new entity enumeration icon chooser.
   *
   * @param enumeration the enumeration to display in this combo box
   */
  public EnumerationIconChooser(Class<E> enumeration) {
    super();

    this.enumeration = enumeration;

    try {
      this.icons = (ImageIcon[]) enumeration.getMethod("getIcons").invoke(null);
      for (int i = 0; i < icons.length; i++) {
        addItem(icons[i]);
      }
    } catch (NoSuchMethodException ex) {
      System.err.println(
          "The method 'getIcons()' is missing in enumeration " + enumeration.getName());
      ex.printStackTrace();
      System.exit(1);
    } catch (IllegalAccessException ex) {
      System.err.println(
          "Cannot access method 'getIcons()' in enumeration "
              + enumeration.getName()
              + ": ex.getMessage()");
      ex.printStackTrace();
      System.exit(1);
    } catch (InvocationTargetException ex) {
      ex.getCause().printStackTrace();
      System.exit(1);
    }
  }
    public void addGetter(MetaBeanProperty property) throws Exception {
      MetaMethod getter = property.getGetter();

      // GENERATE private boolean <prop>Set;

      String flagName = String.format("%sSet", property.getName());
      visitor.visitField(
          Opcodes.ACC_PRIVATE, flagName, Type.BOOLEAN_TYPE.getDescriptor(), null, null);

      addConventionGetter(getter.getName(), flagName, property);

      String getterName = getter.getName();
      Class<?> returnType = getter.getReturnType();

      // If it's a boolean property, there can be get or is type variants.
      // If this class has both, decorate both.
      if (returnType.equals(Boolean.TYPE)) {
        boolean getterIsIsMethod = getterName.startsWith("is");
        String propertyNameComponent = getterName.substring(getterIsIsMethod ? 2 : 3);
        String alternativeGetterName =
            String.format("%s%s", getterIsIsMethod ? "get" : "is", propertyNameComponent);

        try {
          type.getMethod(alternativeGetterName);
          addConventionGetter(alternativeGetterName, flagName, property);
        } catch (NoSuchMethodException e) {
          // ignore, no method to override
        }
      }
    }
Beispiel #23
0
 private String getExifData(ImagePlus imp) {
   FileInfo fi = imp.getOriginalFileInfo();
   if (fi == null) return null;
   String directory = fi.directory;
   String name = fi.fileName;
   if (directory == null) return null;
   if ((name == null || name.equals("")) && imp.getStack().isVirtual())
     name = imp.getStack().getSliceLabel(imp.getCurrentSlice());
   if (name == null || !(name.endsWith("jpg") || name.endsWith("JPG"))) return null;
   String path = directory + name;
   String metadata = null;
   try {
     Class c = IJ.getClassLoader().loadClass("Exif_Reader");
     if (c == null) return null;
     String methodName = "getMetadata";
     Class[] argClasses = new Class[1];
     argClasses[0] = methodName.getClass();
     Method m = c.getMethod("getMetadata", argClasses);
     Object[] args = new Object[1];
     args[0] = path;
     Object obj = m.invoke(null, args);
     metadata = obj != null ? obj.toString() : null;
   } catch (Exception e) {
     return null;
   }
   if (metadata != null && !metadata.startsWith("Error:")) return metadata;
   else return null;
 }
Beispiel #24
0
 static void javac(String... args) throws Exception {
   Class c = Class.forName("pl.wcislo.sbql4j.tools.javac.Main", true, cl);
   int status =
       (Integer)
           c.getMethod("compile", new Class[] {String[].class})
               .invoke(c.newInstance(), new Object[] {args});
   if (status != 0) throw new Exception("javac failed: status=" + status);
 }
 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();
   }
 }
Beispiel #26
0
  public static void invokeSetMethodCaseInsensitive(Object obj, String prop, String value)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    String alternateMethodName = null;
    Class cl = obj.getClass();

    String setMeth = "set" + prop;

    Method[] methodsList = cl.getMethods();
    boolean methodFound = false;
    int i = 0;
    for (i = 0; i < methodsList.length; ++i) {
      if (methodsList[i].getName().equalsIgnoreCase(setMeth) == true) {
        Class[] parameterTypes = methodsList[i].getParameterTypes();
        if (parameterTypes.length == 1) {
          if (parameterTypes[0].getName().equals("java.lang.String")) {
            methodFound = true;
            break;
          } else alternateMethodName = methodsList[i].getName();
        }
      }
    }
    if (methodFound == true) {
      Object[] params = {value};
      methodsList[i].invoke(obj, params);
      return;
    }
    if (alternateMethodName != null) {
      try {
        // try int method
        Class[] cldef = {Integer.TYPE};
        Method meth = cl.getMethod(alternateMethodName, cldef);
        Object[] params = {Integer.valueOf(value)};
        meth.invoke(obj, params);
        return;
      } catch (NoSuchMethodException nsmex) {
        // try boolean method
        Class[] cldef = {Boolean.TYPE};
        Method meth = cl.getMethod(alternateMethodName, cldef);
        Object[] params = {Boolean.valueOf(value)};
        meth.invoke(obj, params);
        return;
      }

    } else throw new NoSuchMethodException(setMeth);
  }
  // The default constructor
  public CrownCounselIndexGetList_Access() {
    String traceProp = null;
    if ((traceProp = System.getProperty(HOSTPUBLISHER_ACCESSBEAN_TRACE)) != null) {
      try {
        Class c = Class.forName(HOSTPUBLISHER_ACCESSTRACE_OBJECT);
        Method m = c.getMethod("getInstance", null);
        o = m.invoke(null, null);
        Class parmTypes[] = {String.class};
        m = c.getMethod("initTrace", parmTypes);
        Object initTraceArgs[] = {traceProp};
        BitSet tracingBS = (BitSet) m.invoke(o, initTraceArgs);
        Class parmTypes2[] = {Object.class, String.class};
        traceMethod = c.getMethod("trace", parmTypes2);
        tracing = tracingBS.get(HOSTPUBLISHER_ACCESSBEAN_TRACING);
        Class parmTypes3[] = {String.class, HttpSession.class};
        auditMethod = c.getMethod("audit", parmTypes3);
        auditing = tracingBS.get(HOSTPUBLISHER_ACCESSBEAN_AUDITING);
      } catch (Exception e) {
        // no tracing will be done
        System.err.println(
            (new Date(System.currentTimeMillis())).toString()
                + " hostpublisher.accessbean.trace="
                + traceProp
                + ", Exception="
                + e.toString());
      }
    }

    if (tracing == true) {
      traceArgs[0] = this;
      traceArgs[1] = " CrownCounselIndexGetList_Access()";
      try {
        traceMethod.invoke(o, traceArgs);
      } catch (Exception x) {
        System.err.println(
            (new Date(System.currentTimeMillis())).toString()
                + " traceMethod.invoke(null, traceArgs)"
                + ", Exception="
                + x.toString());
      }
    }
    inputProps = new CrownCounselIndexGetList_Properties();
    return;
  }
Beispiel #28
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));
  }
 public void close() {
   if (jusl) {
     try {
       // Call java.util.ServiceLoader.reload
       Method reloadMethod = loaderClass.getMethod("reload");
       reloadMethod.invoke(loader);
     } catch (Exception e) {; // Ignore problems during a call to reload.
     }
   }
 }
  public int test(String[] args) throws Exception {
    Class cl =
        Class.forName(
            "org.apache.harmony.vts.test.vm.jvms.classFile.attributes.annotation.annotationDefault.methodinfo13.annotation13");
    Object o = cl.getMethod("value", new Class[] {}).getDefaultValue();

    if ("org.apache.harmony.vts.test.vm.jvms.classFile.attributes.annotation.annotationDefault.methodinfo13.annotation13ann"
        .equals(((Annotation) o).annotationType().getName())) return 104;
    return 105;
  }