コード例 #1
0
  @Override
  protected void actionPerformed(GuiButton guiButton) {
    if (guiButton.enabled) {
      if (guiButton.id == this.btnOpenDir.id) {
        boolean success = false;

        try {
          Class c = Class.forName("java.awt.Desktop");
          Object m = c.getMethod("getDesktop", new Class[0]).invoke((Object) null, new Object[0]);
          c.getMethod("browse", new Class[] {URI.class})
              .invoke(m, new Object[] {Settings.schematicDirectory.toURI()});
        } catch (Throwable e) {
          success = true;
        }

        if (success) {
          Settings.logger.logInfo("Opening via Sys class!");
          Sys.openURL("file://" + Settings.schematicDirectory.getAbsolutePath());
        }
      } else if (guiButton.id == this.btnDone.id) {
        loadSchematic();
        this.mc.displayGuiScreen(this.prevGuiScreen);
      } else {
        this.guiSchematicLoadSlot.actionPerformed(guiButton);
      }
    }
  }
コード例 #2
0
ファイル: ShopConnector.java プロジェクト: TryFailRepeat/ds
  static {
    try {
      final Properties properties = new Properties();
      try (InputStream byteSource =
          ShopConnector.class.getResourceAsStream("shop-mysql.properties")) {
        properties.load(byteSource);
      }

      final Class<?> dataSourceClass =
          Class.forName(
              "com.mysql.jdbc.jdbc2.optional.MysqlDataSource",
              true,
              Thread.currentThread().getContextClassLoader());
      final DataSource dataSource = (DataSource) dataSourceClass.newInstance();
      dataSourceClass
          .getMethod("setURL", String.class)
          .invoke(dataSource, properties.get("connectionUrl"));
      dataSourceClass
          .getMethod("setCharacterEncoding", String.class)
          .invoke(dataSource, properties.get("characterEncoding"));
      dataSourceClass
          .getMethod("setUser", String.class)
          .invoke(dataSource, properties.get("alias"));
      dataSourceClass
          .getMethod("setPassword", String.class)
          .invoke(dataSource, properties.get("password"));
      DATA_SOURCE = dataSource;
    } catch (final Exception exception) {
      throw new ExceptionInInitializerError(exception);
    }
  }
コード例 #3
0
ファイル: Base64.java プロジェクト: wangsongyan/zip-signer
  static {
    Class<Object> clazz;

    logger = LoggerManager.getLogger(Base64.class.getName());

    try {
      clazz = (Class<Object>) Class.forName("android.util.Base64");
      // Looking for encode( byte[] input, int flags)
      aMethod = clazz.getMethod("encode", byte[].class, Integer.TYPE);
      logger.info(clazz.getName() + " is available.");
    } catch (ClassNotFoundException x) {
    } // Ignore
    catch (Exception x) {
      logger.error("Failed to initialize use of android.util.Base64", x);
    }

    try {
      clazz = (Class<Object>) Class.forName("org.bouncycastle.util.encoders.Base64Encoder");
      bEncoder = clazz.newInstance();
      // Looking for encode( byte[] input, int offset, int length, OutputStream output)
      bMethod =
          clazz.getMethod("encode", byte[].class, Integer.TYPE, Integer.TYPE, OutputStream.class);
      logger.info(clazz.getName() + " is available.");
    } catch (ClassNotFoundException x) {
    } // Ignore
    catch (Exception x) {
      logger.error("Failed to initialize use of org.bouncycastle.util.encoders.Base64Encoder", x);
    }

    if (aMethod == null && bMethod == null)
      throw new IllegalStateException("No base64 encoder implementation is available.");
  }
コード例 #4
0
  public void setParameterValues(Properties parameters) {
    String enumClassName = parameters.getProperty("enumClass");
    try {
      enumClass = Class.forName(enumClassName).asSubclass(Enum.class);
    } catch (ClassNotFoundException cfne) {
      throw new HibernateException("Enum class not found", cfne);
    }

    String identifierMethodName =
        parameters.getProperty("identifierMethod", DEFAULT_IDENTIFIER_METHOD_NAME);

    try {
      identifierMethod = enumClass.getMethod(identifierMethodName, new Class[0]);
      identifierType = identifierMethod.getReturnType();
    } catch (Exception e) {
      throw new HibernateException("Failed to obtain identifier method", e);
    }

    type = (NullableType) TypeFactory.basic(identifierType.getName());

    if (type == null)
      throw new HibernateException("Unsupported identifier type " + identifierType.getName());

    sqlTypes = new int[] {type.sqlType()};

    String valueOfMethodName =
        parameters.getProperty("valueOfMethod", DEFAULT_VALUE_OF_METHOD_NAME);

    try {
      valueOfMethod = enumClass.getMethod(valueOfMethodName, new Class[] {identifierType});
    } catch (Exception e) {
      throw new HibernateException("Failed to obtain valueOf method", e);
    }
  }
コード例 #5
0
  private void calculateWrapSize(Rectangle bounds) {
    if (myWrapSize.width == -1 || myWrapSize.height == -1) {
      try {
        Object viewObject = myComponent.getViewInfo().getViewObject();
        Class<?> viewClass = viewObject.getClass();

        viewClass.getMethod("forceLayout").invoke(viewObject);
        viewClass
            .getMethod("measure", int.class, int.class)
            .invoke(viewObject, WRAP_CONTENT, WRAP_CONTENT);

        if (myWrapSize.width == -1) {
          myWrapSize.width = (Integer) viewClass.getMethod("getMeasuredWidth").invoke(viewObject);
        }
        if (myWrapSize.height == -1) {
          myWrapSize.height = (Integer) viewClass.getMethod("getMeasuredHeight").invoke(viewObject);
        }
      } catch (Throwable e) {
        if (myWrapSize.width == -1) {
          myWrapSize.width = bounds.width;
        }
        if (myWrapSize.height == -1) {
          myWrapSize.height = bounds.height;
        }
      }
    }
  }
コード例 #6
0
  /**
   * @param context
   * @param simpleOnScaleGestureListener
   */
  public ScaleGestureDetector(
      Context context, SimpleOnScaleGestureListener simpleOnScaleGestureListener) {
    try {
      // check if class is available
      Class.forName("android.view.ScaleGestureDetector");

      // load class and methods
      Class<?> classRealScaleGestureDetector =
          Class.forName("com.jjoe64.graphview.compatible.RealScaleGestureDetector");
      method_getScaleFactor = classRealScaleGestureDetector.getMethod("getScaleFactor");
      method_isInProgress = classRealScaleGestureDetector.getMethod("isInProgress");
      method_onTouchEvent =
          classRealScaleGestureDetector.getMethod("onTouchEvent", MotionEvent.class);

      // create real ScaleGestureDetector
      Constructor<?> constructor =
          classRealScaleGestureDetector.getConstructor(
              Context.class, getClass(), SimpleOnScaleGestureListener.class);
      realScaleGestureDetector =
          constructor.newInstance(context, this, simpleOnScaleGestureListener);
    } catch (Exception e) {
      // not available
      Log.w("com.jjoe64.graphview", "*** WARNING *** No scaling available for graphs. Exception:");
      e.printStackTrace();
    }
  }
コード例 #7
0
ファイル: ReflectUtils.java プロジェクト: johnnyshaw/javautil
 @SuppressWarnings({"unchecked", "rawtypes"})
 public static Object invokeGetMethod(Class claszz, Object o, String name) {
   Object ret = null;
   try {
     String[] names = name.split("/.");
     for (int i = 0; i < names.length; i++) {
       if (names.length > i) {
         if (ret != null) {
           o = ret;
         }
         Method method2 = null;
         if (names[i].length() > 7 && "(Other)".equals(names[i].substring(0, 7))) {
           method2 = claszz.getMethod(names[i].substring(7));
         } else {
           method2 = claszz.getMethod("get" + firstCharUpperCase(names[i]));
         }
         ret = method2.invoke(o);
         if (ret != null) {
           claszz = ret.getClass();
         } else {
           return null;
         }
       }
     }
   } catch (Exception e) {
     logger.error(e);
   }
   return ret;
 }
コード例 #8
0
  static {
    if (!Boolean.getBoolean(GridSystemProperties.GG_JETTY_LOG_NO_OVERRIDE)) {
      String ctgrJetty = "org.eclipse.jetty"; // WARN for this category.
      String ctgrJettyUtil = "org.eclipse.jetty.util.log"; // ERROR for this...
      String ctgrJettyUtilComp = "org.eclipse.jetty.util.component"; // ...and this.

      try {
        Class<?> logCls = Class.forName("org.apache.log4j.Logger");

        Object logJetty = logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJetty);
        Object logJettyUtil =
            logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJettyUtil);
        Object logJettyUtilComp =
            logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJettyUtilComp);

        Class<?> lvlCls = Class.forName("org.apache.log4j.Level");

        Object warnLvl = lvlCls.getField("WARN").get(null);
        Object errLvl = lvlCls.getField("ERROR").get(null);

        logJetty.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, warnLvl);
        logJettyUtil.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, errLvl);
        logJettyUtilComp.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, errLvl);
      } catch (Exception ignored) {
        // No-op.
      }
    }
  }
コード例 #9
0
    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);
    }
コード例 #10
0
 public static void main(String[] args) throws Exception {
   // 直接获取类
   // Class<?> classType = InvokeTester.class;
   // 通过完整的类型路径获取类
   Class<?> classType = Class.forName("reflect.invokeTester.InvokeTester");
   // 使用newInstance创建对象
   // Object invokeTester = classType.newInstance();
   // 使用默认构造函数获取对象
   Object invokeTester = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});
   // 获取InvokeTester类的add()方法
   Method addMethod = classType.getMethod("add", new Class[] {int.class, int.class});
   // 调用invokeTester对象上的add()方法
   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});
   // 调用invokeTester对象的echo()方法
   result = echoMethod.invoke(invokeTester, new Object[] {"Hello"});
   System.out.println((String) result);
   // 创建有参构造函数的类对象
   Object invokeTester1 =
       classType
           .getConstructor(new Class[] {String.class})
           .newInstance(new Object[] {new String("测试一个带参数的构造调用")});
   // 获取方法方式相同
   Method getStrMethod = classType.getMethod("getStr");
   Object str = getStrMethod.invoke(invokeTester1);
   System.out.println(str);
 }
コード例 #11
0
  /**
   * Attach and load an agent class.
   *
   * @param log Log used if the agent cannot be loaded.
   * @param agentJar absolute path to the agent jar.
   * @param vmClass VirtualMachine.class from tools.jar.
   */
  private static void loadAgent(Config config, Log log, String agentJar, Class<?> vmClass) {
    try {

      // addAttach(config,log);

      // first obtain the PID of the currently-running process
      // ### this relies on the undocumented convention of the
      // RuntimeMXBean's
      // ### name starting with the PID, but there appears to be no other
      // ### way to obtain the current process' id, which we need for
      // ### the attach process
      RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
      String pid = runtime.getName();
      if (pid.indexOf("@") != -1) pid = pid.substring(0, pid.indexOf("@"));
      log.info("Instrumentation", "pid:" + pid);
      // JDK1.6: now attach to the current VM so we can deploy a new agent
      // ### this is a Sun JVM specific feature; other JVMs may offer
      // ### this feature, but in an implementation-dependent way
      Object vm =
          vmClass
              .getMethod("attach", new Class<?>[] {String.class})
              .invoke(null, new Object[] {pid});
      // now deploy the actual agent, which will wind up calling
      // agentmain()
      vmClass
          .getMethod("loadAgent", new Class[] {String.class})
          .invoke(vm, new Object[] {agentJar});
      vmClass.getMethod("detach", new Class[] {}).invoke(vm, new Object[] {});
    } catch (Throwable t) {
      // Log the message from the exception. Don't log the entire
      // stack as this is expected when running on a JDK that doesn't
      // support the Attach API.
      log.log(Log.LEVEL_ERROR, "Instrumentation", t);
    }
  }
コード例 #12
0
 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;
 }
コード例 #13
0
ファイル: Utility.java プロジェクト: phan-pivotal/OSS
  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;
      }
    }
  }
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void onCreateReflectionCalls(Gallery aGallery, Activity activity) {
    try {
      // same as gallery.setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
      Class GalleryClass = aGallery.getClass();
      Method setSystemMethod = GalleryClass.getMethod("setSystemUiVisibility", int.class);
      setSystemMethod.invoke(aGallery, 1);

      Class ActivityClass = activity.getClass();
      Method getActionBar = ActivityClass.getMethod("getActionBar");
      Object objectActionBar = getActionBar.invoke(activity);

      Class ActionBarClass = objectActionBar.getClass();
      Method setDisplayShowTitleEnabled =
          ActionBarClass.getMethod("setDisplayShowTitleEnabled", boolean.class);
      setDisplayShowTitleEnabled.invoke(objectActionBar, false);

    } catch (NoSuchMethodException e) {
      // ignore
      // TODO: handle exception
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      // e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      // e.printStackTrace();
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      // e.printStackTrace();
    }
  }
コード例 #15
0
 static void init() {
   try {
     awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
     translucencyClass = Class.forName("com.sun.awt.AWTUtilities$Translucency");
     if (translucencyClass.isEnum()) {
       Object[] kinds = translucencyClass.getEnumConstants();
       if (kinds != null) {
         PERPIXEL_TRANSPARENT = kinds[0];
         TRANSLUCENT = kinds[1];
         PERPIXEL_TRANSLUCENT = kinds[2];
       }
     }
     mIsTranslucencySupported =
         awtUtilitiesClass.getMethod("isTranslucencySupported", translucencyClass);
     mIsTranslucencyCapable =
         awtUtilitiesClass.getMethod("isTranslucencyCapable", GraphicsConfiguration.class);
     mSetWindowShape = awtUtilitiesClass.getMethod("setWindowShape", Window.class, Shape.class);
     mSetWindowOpacity =
         awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
     mSetWindowOpaque =
         awtUtilitiesClass.getMethod("setWindowOpaque", Window.class, boolean.class);
   } catch (NoSuchMethodException ex) {
     Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
   } catch (SecurityException ex) {
     Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
   } catch (ClassNotFoundException ex) {
     Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
コード例 #16
0
  /** Finds a given annotation on a property getter method. */
  public static <A extends Annotation> A getAnnotationFromPropertyGetter(
      Class<A> annotationType, Class<?> entityClass, String propertyName) {
    // TODO: support for private getters? -> need to recursively search
    // superclasses as well.

    Method getter = null;
    try {
      getter =
          entityClass.getMethod(
              "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1));
    } catch (Exception e) {
      // Try isXXX
      try {
        getter =
            entityClass.getMethod(
                "is" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1));
      } catch (Exception e1) {
        // No getter found.
      }
    }
    if (getter != null && getter.isAnnotationPresent(annotationType)) {
      return getter.getAnnotation(annotationType);
    }
    return null;
  }
コード例 #17
0
ファイル: LE.java プロジェクト: allanfish/yufei-facetime
 /**
  * 获取一个对象的属性值(除了传统的Getter,还可以容忍PUBLIC Field)。<br>
  * </> 不查找方法(没有使用CE),直接尝试调用一个对象各类可能的方法(多是getter应用)<br>
  * </> 按照 obj.property. obj.getProperty(), obj.isProperty(), obj.property(),. 的顺序依次尝试执行 如果有异常扔出
  * FailToInvokingException
  *
  * @param object 实际对象本身
  * @param property 对象的属性
  * @return 对象的属性值
  */
 public static Object getPropertyValue(Object object, String property) {
   Class<?> clzz = object.getClass();
   try {
     Field fld = object.getClass().getField(property);
     return fld.get(object);
   } catch (Throwable t) {
     Method m = null;
     try {
       m = clzz.getMethod("get" + StringUtils.capitalize(property));
     } catch (NoSuchMethodException t1) {
       try {
         m = clzz.getMethod("is" + StringUtils.capitalize(property));
       } catch (NoSuchMethodException t2) {
         try {
           m = clzz.getMethod(property);
         } catch (NoSuchMethodException e) {
           throw new FailToGetValueException(
               "Can NOT find any public property or getter named [ %s ] on class[ %s ]",
               property, object.getClass());
         }
       }
     }
     try {
       return m.invoke(object);
     } catch (Throwable e) {
       throw new FailToGetValueException(
           e, "Get property[%s] value on class[%s] failed.", property, object.getClass());
     }
   }
 }
コード例 #18
0
 /*
  *  Use reflection to make a test compilable on not Mac OS X
  */
 private static void enableFullScreen(Window window) {
   try {
     Class fullScreenUtilities = Class.forName("com.apple.eawt.FullScreenUtilities");
     Method setWindowCanFullScreen =
         fullScreenUtilities.getMethod("setWindowCanFullScreen", Window.class, boolean.class);
     setWindowCanFullScreen.invoke(fullScreenUtilities, window, true);
     Class fullScreenListener = Class.forName("com.apple.eawt.FullScreenListener");
     Object listenerObject =
         Proxy.newProxyInstance(
             fullScreenListener.getClassLoader(),
             new Class[] {fullScreenListener},
             new InvocationHandler() {
               @Override
               public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                 switch (method.getName()) {
                   case "windowEnteringFullScreen":
                     windowEnteringFullScreen = true;
                     break;
                   case "windowEnteredFullScreen":
                     windowEnteredFullScreen = true;
                     break;
                 }
                 return null;
               }
             });
     Method addFullScreenListener =
         fullScreenUtilities.getMethod(
             "addFullScreenListenerTo", Window.class, fullScreenListener);
     addFullScreenListener.invoke(fullScreenUtilities, window, listenerObject);
   } catch (Exception e) {
     throw new RuntimeException("FullScreen utilities not available", e);
   }
 }
コード例 #19
0
ファイル: Mirror.java プロジェクト: jekey/nutz
 /**
  * 根据一个字段名和字段类型获取 Setter
  *
  * @param fieldName 字段名
  * @param paramType 字段类型
  * @return 方法
  * @throws NoSuchMethodException 没找到 Setter
  */
 public Method getSetter(String fieldName, Class<?> paramType) throws NoSuchMethodException {
   try {
     String setterName = "set" + Strings.capitalize(fieldName);
     try {
       return klass.getMethod(setterName, paramType);
     } catch (Throwable e) {
       try {
         return klass.getMethod(fieldName, paramType);
       } catch (Throwable e1) {
         Mirror<?> type = Mirror.me(paramType);
         for (Method method : klass.getMethods()) {
           if (method.getParameterTypes().length == 1)
             if (method.getName().equals(setterName) || method.getName().equals(fieldName)) {
               if (null == paramType || type.canCastToDirectly(method.getParameterTypes()[0]))
                 return method;
             }
         }
         // 还是没有? 会不会是包装类型啊?
         if (!paramType.isPrimitive()) {
           Class<?> p = unWrapper();
           if (null != p) return getSetter(fieldName, p);
         }
         throw new RuntimeException();
       }
     }
   } catch (Throwable e) {
     throw Lang.makeThrow(
         NoSuchMethodException.class,
         "Fail to find setter for [%s]->[%s(%s)]",
         klass.getName(),
         fieldName,
         paramType.getName());
   }
 }
コード例 #20
0
ファイル: CarOfReflect.java プロジェクト: ningg/SpringLearn
  static Car initByDefaultConst()
      throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
          InvocationTargetException, InstantiationException {
    // 1. 通过类加载器,获取Car的Class对象
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Class clazz = classLoader.loadClass("top.ningg.spring.ioc.Car");

    // 获取Car的Class对象的其他方法:
    // Class clazz = Class.forName("top.ningg.spring.ioc.Car");
    // Class clazz = Car.class;
    // Class clazz = new Car().getClass();

    // 思考: 上述几种获取 Class 对象的方式, 哪种最优?

    // 2. 获取Car的Class中的默认构造方法,创建Car对象
    // 补充: getDeclaredConstructor((Class[])null), 使用 Class[] 是因为底层使用
    // Object[] 来匹配构造方法的输入参数, 如果使用(Class)null, 则抛出异常.
    Constructor constructor = clazz.getDeclaredConstructor((Class[]) null);
    Car car = (Car) constructor.newInstance();

    // 3. 获取Car的Class中的setter方法,设置属性
    Method setBrand = clazz.getMethod("setBrand", String.class);
    setBrand.invoke(car, "new Brand");
    Method setColor = clazz.getMethod("setColor", String.class);
    setColor.invoke(car, "Red");
    Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
    setMaxSpeed.invoke(car, 1000);

    return car;
  }
コード例 #21
0
  public boolean endCall() {
    if (_prevRingerMode == null) {
      _prevRingerMode = _audioManager.getRingerMode();
    }

    _audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);

    try {
      String serviceManagerName = "android.os.ServiceManager";
      String serviceManagerNativeName = "android.os.ServiceManagerNative";
      String telephonyName = "com.android.internal.telephony.ITelephony";

      Class<?> telephonyClass = Class.forName(telephonyName);
      Class<?> telephonyStubClass = telephonyClass.getClasses()[0];
      Class<?> serviceManagerClass = Class.forName(serviceManagerName);
      Class<?> serviceManagerNativeClass = Class.forName(serviceManagerNativeName);

      Binder tmpBinder = new Binder();
      tmpBinder.attachInterface(null, "fake");
      Method tempInterfaceMethod =
          serviceManagerNativeClass.getMethod("asInterface", IBinder.class);
      Object serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
      Method getService = serviceManagerClass.getMethod("getService", String.class);
      IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone");

      Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class);
      Object telephonyObject = serviceMethod.invoke(null, retbinder);
      Method telephonyEndCall = telephonyClass.getMethod("endCall");
      telephonyEndCall.invoke(telephonyObject);
      return true;
    } catch (Exception e) {
      Log.e(TAG, "Could not connect to telephony subsystem", e);
      return false;
    }
  }
コード例 #22
0
  /**
   * Define an attribute. Explicit definition of an attribute. Reflection is used to locate the
   * actual getter and setter methods.
   *
   * @param attrInfo ModelMBeanAttributeInfo.
   */
  public synchronized void defineAttribute(ModelMBeanAttributeInfo attrInfo) {
    if (_object == null) throw new IllegalStateException("No Object");

    _dirty = true;

    String name = attrInfo.getName();
    String uName = name.substring(0, 1).toUpperCase() + name.substring(1);
    Class oClass = _object.getClass();

    try {
      Class type = TypeUtil.fromName(attrInfo.getType());
      if (type == null)
        type = Thread.currentThread().getContextClassLoader().loadClass(attrInfo.getType());

      Method getter = null;
      Method setter = null;

      if (attrInfo.isReadable())
        getter =
            oClass.getMethod((attrInfo.isIs() ? "is" : "get") + uName, (java.lang.Class[]) null);

      if (attrInfo.isWritable()) setter = oClass.getMethod("set" + uName, new Class[] {type});

      _getter.put(name, getter);
      _setter.put(name, setter);
      _attributes.add(attrInfo);
    } catch (Exception e) {
      log.warn(LogSupport.EXCEPTION, e);
      throw new IllegalArgumentException(e.toString());
    }
  }
コード例 #23
0
  private Object getValueFromClass(Object object, String field) {

    Class c = object.getClass();
    Method method = null;
    try {
      method = c.getMethod("get" + firstToUp(field), null);
    } catch (NoSuchMethodException mex1) {
      try {
        method = c.getMethod("is" + firstToUp(field), null);
      } catch (NoSuchMethodException mex2) {
        return "";
      } catch (SecurityException sex2) {
        return "";
      }
    } catch (SecurityException sex1) {
      return "";
    }

    try {
      return method.invoke(object, null);
    } catch (Exception ex) {
      ex.printStackTrace();
      return "";
    }
  }
コード例 #24
0
  @Before
  public void resetIndividualClassLoader() throws Exception {
    sharedCache = new IndividualClassLoader.Cache();
    l1 = new IndividualClassLoader("instrumentertest", sharedCache);
    l2 = new IndividualClassLoader("instrumentertest", sharedCache);

    // Set up noop RobotMonitors.

    SandboxedRobotPlayer.Pauser pauser = () -> {};
    SandboxedRobotPlayer.Killer killer = () -> {};

    final Class<?> monitor1 = l1.loadClass("battlecode.instrumenter.inject.RobotMonitor");
    monitor1
        .getMethod(
            "init", SandboxedRobotPlayer.Pauser.class, SandboxedRobotPlayer.Killer.class, int.class)
        .invoke(null, pauser, killer, 0);
    monitor1.getMethod("setBytecodeLimit", int.class).invoke(null, Integer.MAX_VALUE);

    final Class<?> monitor2 = l2.loadClass("battlecode.instrumenter.inject.RobotMonitor");
    monitor2
        .getMethod(
            "init", SandboxedRobotPlayer.Pauser.class, SandboxedRobotPlayer.Killer.class, int.class)
        .invoke(null, pauser, killer, 0);
    monitor2.getMethod("setBytecodeLimit", int.class).invoke(null, Integer.MAX_VALUE);
  }
コード例 #25
0
ファイル: ClassUtils.java プロジェクト: PAMSE/APGBench
  /**
   * Returns the desired Method much like <code>Class.getMethod</code>, however it ensures that the
   * returned Method is from a public class or interface and not from an anonymous inner class. This
   * means that the Method is invokable and doesn't fall foul of Java bug <a
   * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>). <code>
   * <pre>Set set = Collections.unmodifiableSet(...);
   *  Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty",  new Class[0]);
   *  Object result = method.invoke(set, new Object[]);</pre></code>
   *
   * @param cls the class to check, not null
   * @param methodName the name of the method
   * @param parameterTypes the list of parameters
   * @return the method
   * @throws NullPointerException if the class is null
   * @throws SecurityException if a a security violation occured
   * @throws NoSuchMethodException if the method is not found in the given class or if the metothod
   *     doen't conform with the requirements
   */
  public static Method getPublicMethod(Class<?> cls, String methodName, Class<?> parameterTypes[])
      throws SecurityException, NoSuchMethodException {

    Method declaredMethod = cls.getMethod(methodName, parameterTypes);
    if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
      return declaredMethod;
    }

    List<Class<?>> candidateClasses = new ArrayList<Class<?>>();
    candidateClasses.addAll(getAllInterfaces(cls));
    candidateClasses.addAll(getAllSuperclasses(cls));

    for (Class<?> candidateClass : candidateClasses) {
      if (!Modifier.isPublic(candidateClass.getModifiers())) {
        continue;
      }
      Method candidateMethod;
      try {
        candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
      } catch (NoSuchMethodException ex) {
        continue;
      }
      if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
        return candidateMethod;
      }
    }

    throw new NoSuchMethodException(
        "Can't find a public method for " + methodName + " " + ArrayUtils.toString(parameterTypes));
  }
コード例 #26
0
 /**
  * Specialized method. It's behavior is isolated and different enough from the usual invocation
  * that custom code is warranted.
  */
 @SuppressWarnings("restriction")
 private static long[] OS_object_getInstanceVariable(long delegateId, byte[] name)
     throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
         SecurityException, NoSuchMethodException {
   Class<OS> clazz = OS.class;
   Method method = null;
   Class<?> PTR_CLASS = C.PTR_SIZEOF == 8 ? long.class : int.class;
   if (PTR_CLASS == long.class) {
     method =
         clazz.getMethod(
             "object_getInstanceVariable",
             new Class[] { // $NON-NLS-1$
               long.class, byte[].class, long[].class
             });
     long[] resultPtr = new long[1];
     method.invoke(null, new Object[] {new Long(delegateId), name, resultPtr});
     return resultPtr;
   } else {
     method =
         clazz.getMethod(
             "object_getInstanceVariable",
             new Class[] { // $NON-NLS-1$
               int.class, byte[].class, int[].class
             });
     int[] resultPtr = new int[1];
     method.invoke(null, new Object[] {new Integer((int) delegateId), name, resultPtr});
     return new long[] {resultPtr[0]};
   }
 }
コード例 #27
0
ファイル: Viewport.java プロジェクト: TurboVNC/turbovnc
  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());
    }
  }
コード例 #28
0
  /**
   * Processes this instance's methodNameMap using reflection. The parameters passed in should
   * contain the methods that have been loaded into the methodNameMap and they will be executed
   * using reflection and returned.
   *
   * @param player
   * @param gamePlayer
   * @return List<Integer>
   */
  public List<Integer> processMethodNameMap(Player player, GamePlayer gamePlayer) {

    List<Integer> processedValues = new ArrayList<Integer>();
    Class<Player> playerClass = Player.class;
    Class<GamePlayer> gamePlayerClass = GamePlayer.class;
    for (Entry<String, String> entry : methodNameMap.entrySet()) {
      try {
        String ruleType = entry.getKey();
        String methodName = entry.getValue();
        String completeMethodName =
            "get" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
        Integer value = null;
        if (player != null && ruleType.startsWith("PLAYER")) {
          Method methodToInvoke = playerClass.getMethod(completeMethodName);
          value = (Integer) methodToInvoke.invoke(player, new Object[0]);
        }
        if (gamePlayer != null && ruleType.startsWith("GAMEPLAYER")) {
          Method methodToInvoke = gamePlayerClass.getMethod(completeMethodName);
          value = (Integer) methodToInvoke.invoke(gamePlayer, new Object[0]);
        }
        if (value != null) {
          processedValues.add(value);
        }
      } catch (Exception e) {

        // Needs better error handling
        e.printStackTrace();
      }
    }
    return processedValues;
  }
コード例 #29
0
  static void testReflectionTest3() {
    try {
      String imei = taintedString();

      Class c = Class.forName("de.ecspride.ReflectiveClass");
      Object o = c.newInstance();
      Method m = c.getMethod("setIme" + "i", String.class);
      m.invoke(o, imei);

      Method m2 = c.getMethod("getImei");
      String s = (String) m2.invoke(o);

      assert (getTaint(s) != 0);
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #30
0
  @Test
  public void nestedSelfRefsInStringContentWithoutParentFile()
      throws NoSuchMethodException, ClassNotFoundException, IOException {

    String schemaContents =
        IOUtils.toString(
            CodeGenerationHelper.class.getResource("/schema/ref/nestedSelfRefsReadAsString.json"));
    JCodeModel codeModel = new JCodeModel();
    new SchemaMapper().generate(codeModel, "NestedSelfRefsInString", "com.example", schemaContents);

    codeModel.build(schemaRule.getGenerateDir());

    ClassLoader classLoader = schemaRule.compile();

    Class<?> nestedSelfRefs = classLoader.loadClass("com.example.NestedSelfRefsInString");
    assertThat(
        nestedSelfRefs.getMethod("getThings").getReturnType().getSimpleName(), equalTo("List"));

    Class<?> listEntryType =
        (Class<?>)
            ((ParameterizedType) nestedSelfRefs.getMethod("getThings").getGenericReturnType())
                .getActualTypeArguments()[0];
    assertThat(listEntryType.getName(), equalTo("com.example.Thing"));

    Class<?> thingClass = classLoader.loadClass("com.example.Thing");
    assertThat(
        thingClass.getMethod("getNamespace").getReturnType().getSimpleName(), equalTo("String"));
    assertThat(thingClass.getMethod("getName").getReturnType().getSimpleName(), equalTo("String"));
    assertThat(
        thingClass.getMethod("getVersion").getReturnType().getSimpleName(), equalTo("String"));
  }