/** * 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(); } }
private void addClass(Class<?> c) { if (classes.add(c)) { if (c.getSuperclass() != null) { addClass(c.getSuperclass()); } for (Class<?> sc : c.getInterfaces()) { addClass(sc); } for (Class<?> dc : c.getDeclaredClasses()) { addClass(dc); } for (Method m : c.getDeclaredMethods()) { addClass(m.getReturnType()); for (Class<?> p : m.getParameterTypes()) { addClass(p); } } if (c != void.class && dimensions(c) < 2) { Class<?> arrayClass = Array.newInstance(c, 0).getClass(); arrayClasses.put(c, arrayClass); addClass(arrayClass); } } }
private void commandMethods(StringTokenizer t) throws NoSessionException { if (!t.hasMoreTokens()) { env.error("No class specified."); return; } String idClass = t.nextToken(); ReferenceType cls = findClass(idClass); if (cls != null) { List<Method> methods = cls.allMethods(); OutputSink out = env.getOutputSink(); for (int i = 0; i < methods.size(); i++) { Method method = methods.get(i); out.print(method.declaringType().name() + " " + method.name() + "("); Iterator<String> it = method.argumentTypeNames().iterator(); if (it.hasNext()) { while (true) { out.print(it.next()); if (!it.hasNext()) { break; } out.print(", "); } } out.println(")"); } out.show(); } else { // ### Should validate class name syntax. env.failure("\"" + idClass + "\" is not a valid id or class name."); } }
private boolean invokeMethod(String line, PrintWriter out, Method method, String[] fields) throws IllegalAccessException, InvocationTargetException { ArrayList<Object> methodArguments = new ArrayList<Object>(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 2 && parameterTypes[0] == PrintWriter.class && parameterTypes[1] == String.class) { // FIXME: there must be a better way to say "I want to parse the line myself." methodArguments.add(out); methodArguments.add(line); } else { int nextField = 1; for (Class<?> parameterType : parameterTypes) { if (parameterType == PrintWriter.class) { methodArguments.add(out); } else if (parameterType == String.class) { methodArguments.add(fields[nextField++]); } // FIXME: support other common types. "int" seems a likely first candidate. } } method.invoke(handler, methodArguments.toArray()); return true; }
void addIfTestMethod(Method m) { if (m.getAnnotation(Test.class) == null) return; if (!(m.getReturnType().equals(boolean.class) || m.getReturnType().equals(void.class))) throw new RuntimeException("@Test method" + " must return boolean or void"); m.setAccessible(true); // In case it's private, etc. add(m); }
static { try { Map<String, Method> orderedMethods = new TreeMap<String, Method>(); for (Method m : MBeanServerConnection.class.getDeclaredMethods()) { orderedMethods.put(m.toGenericString(), m); } Method[] methods = orderedMethods.values().toArray(new Method[orderedMethods.size()]); Map<String, Method> asynchMethods = new TreeMap<String, Method>(); for (Method asynchMethod : AsynchJMXResponseListener.class.getDeclaredMethods()) { asynchMethods.put(asynchMethod.getName(), asynchMethod); } Map<Method, Byte> m2k = new HashMap<Method, Byte>(methods.length); Map<Byte, Method> k2m = new HashMap<Byte, Method>(methods.length); Map<Byte, Method> k2am = new HashMap<Byte, Method>(methods.length); for (int i = 0; i < methods.length; i++) { m2k.put(methods[i], (byte) i); k2m.put((byte) i, methods[i]); Method asynchMethod = asynchMethods.get(methods[i].getName() + "Response"); if (asynchMethod == null) throw new RuntimeException( "Failed to find asynch handler for [" + methods[i].toGenericString() + "]", new Throwable()); k2am.put((byte) i, asynchMethod); } methodToKey = Collections.unmodifiableMap(m2k); keyToMethod = Collections.unmodifiableMap(k2m); keyToAsynchMethod = Collections.unmodifiableMap(k2am); } catch (Exception ex) { throw new RuntimeException(ex); } }
/** * 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; }
private String doCommand(Object target, String method, String[] args) { if (target == null) ; // System.err.println("Huh? Target should never be null " + // domain); else { String cname = "_" + method.replaceAll("-", "_"); try { Method m = target.getClass().getMethod(cname, new Class[] {String[].class}); return (String) m.invoke(target, new Object[] {args}); } catch (NoSuchMethodException e) { // Ignore } catch (InvocationTargetException e) { if (e.getCause() instanceof IllegalArgumentException) { domain.error( "%s, for cmd: %s, arguments; %s", e.getCause().getMessage(), method, Arrays.toString(args)); } else { domain.warning("Exception in replace: %s", e.getCause()); e.getCause().printStackTrace(); } } catch (Exception e) { domain.warning("Exception in replace: " + e + " method=" + method); e.printStackTrace(); } } return null; }
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; }
/** Creates the URL connection. */ protected URLConnection openConnection(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setDoOutput(true); if (_readTimeout > 0) { try { // only available for JDK 1.5 Method method = conn.getClass().getMethod("setReadTimeout", new Class[] {int.class}); if (method != null) method.invoke(conn, new Object[] {new Integer((int) _readTimeout)}); } catch (Throwable e) { } } conn.setRequestProperty("Content-Type", "x-application/hessian"); if (_basicAuth != null) conn.setRequestProperty("Authorization", _basicAuth); else if (_user != null && _password != null) { _basicAuth = "Basic " + base64(_user + ":" + _password); conn.setRequestProperty("Authorization", _basicAuth); } return conn; }
/* 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); }
// we set an observer to detect VirtualMachineImpl.dispose call // and on dispose we add corresponding VirtualMachineImpl.class to // free VirtualMachimeImpl Class list. protected static void setVMDisposeObserver(final Object vm) { try { Method setDisposeObserverMethod = vm.getClass() .getDeclaredMethod("setDisposeObserver", new Class[] {java.util.Observer.class}); setDisposeObserverMethod.setAccessible(true); setDisposeObserverMethod.invoke( vm, new Object[] { new Observer() { public void update(Observable o, Object data) { if (DEBUG) { System.out.println("got VM.dispose notification"); } addFreeVMImplClass(vm.getClass()); } } }); } catch (Exception exp) { if (DEBUG) { System.out.println("setVMDisposeObserver() got an exception:"); exp.printStackTrace(); } } }
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()); } }
private static double toDouble(Object value) { if (value instanceof Number) { return ((Number) value).doubleValue(); } else if (value instanceof String) { return ScriptRuntime.toNumber((String) value); } else if (value instanceof Scriptable) { if (value instanceof Wrapper) { // XXX: optimize tail-recursion? return toDouble(((Wrapper) value).unwrap()); } else { return ScriptRuntime.toNumber(value); } } else { Method meth; try { meth = value.getClass().getMethod("doubleValue", (Class[]) null); } catch (NoSuchMethodException e) { meth = null; } catch (SecurityException e) { meth = null; } if (meth != null) { try { return ((Number) meth.invoke(value, (Object[]) null)).doubleValue(); } catch (IllegalAccessException e) { // XXX: ignore, or error message? reportConversionError(value, Double.TYPE); } catch (InvocationTargetException e) { // XXX: ignore, or error message? reportConversionError(value, Double.TYPE); } } return ScriptRuntime.toNumber(value.toString()); } }
protected void generateDelegateCode( Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException { String mname = method.getName(); if (jdbc4WrapperMethod(mname)) { generateWrapperDelegateCode(intfcl, genclass, method, iw); return; } Class retType = method.getReturnType(); iw.println("if (proxyConn != null) proxyConn.maybeDirtyTransaction();"); iw.println(); if (mname.equals("close")) { iw.println("if (! this.isDetached())"); iw.println("{"); iw.upIndent(); iw.println("if (creator instanceof Statement)"); iw.upIndent(); iw.println( "parentPooledConnection.markInactiveResultSetForStatement( (Statement) creator, inner );"); iw.downIndent(); iw.println("else if (creator instanceof DatabaseMetaData)"); iw.upIndent(); iw.println("parentPooledConnection.markInactiveMetaDataResultSet( inner );"); iw.downIndent(); iw.println("else if (creator instanceof Connection)"); iw.upIndent(); iw.println("parentPooledConnection.markInactiveRawConnectionResultSet( inner );"); iw.downIndent(); iw.println( "else throw new InternalError(\042Must be Statement or DatabaseMetaData -- Bad Creator: \042 + creator);"); iw.println( "if (creatorProxy instanceof ProxyResultSetDetachable) ((ProxyResultSetDetachable) creatorProxy).detachProxyResultSet( this );"); iw.println("this.detach();"); iw.println("inner.close();"); iw.println("this.inner = null;"); iw.downIndent(); iw.println("}"); } else if (mname.equals("getStatement")) { iw.println("if (creator instanceof Statement)"); iw.upIndent(); iw.println("return (Statement) creatorProxy;"); iw.downIndent(); iw.println("else if (creator instanceof DatabaseMetaData)"); iw.upIndent(); iw.println("return null;"); iw.downIndent(); iw.println( "else throw new InternalError(\042Must be Statement or DatabaseMetaData -- Bad Creator: \042 + creator);"); } else if (mname.equals("isClosed")) { iw.println("return this.isDetached();"); } else super.generateDelegateCode(intfcl, genclass, method, iw); }
static Method lookup(String method) { for (Method m : Method.values()) { if (m.toString().equalsIgnoreCase(method)) { return m; } } return null; }
/** * Given the name and parameters, invoke the method in the builder. This method is required to * invoke the appropriate build method as instructed by the builder XML file. * * @param methodName the name of the method that we would like to invoke. * @param paramClasses the types for each parameter. * @param params the parameters of the method. */ protected void invokeMethod(String methodName, Class<?>[] paramClasses, Object[] params) throws Exception { if (DEBUG) { configuration.root.printError("DEBUG: " + this.getClass().getName() + "." + methodName); } Method method = this.getClass().getMethod(methodName, paramClasses); method.invoke(this, params); }
static <T> T set(Class<T> interf, Object value) { Properties p = new Properties(); Method ms[] = interf.getMethods(); for (Method m : ms) { p.put(m.getName(), value); } return Configurable.createConfigurable(interf, (Map<Object, Object>) p); }
private static int linearSearch(ObjArray methods, Symbol name, Symbol signature) { int len = (int) methods.getLength(); for (int index = 0; index < len; index++) { Method m = (Method) methods.getObjAt(index); if (m.getSignature().equals(signature) && m.getName().equals(name)) { return index; } } return -1; }
private static Method checkForCreatorMethod(Method m) { if (m.getAnnotation(TestObjectCreate.class) == null) return null; if (!m.getReturnType().equals(testClass)) throw new RuntimeException( "@TestObjectCreate " + "must return instance of Class to be tested"); if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) < 1) throw new RuntimeException("@TestObjectCreate " + "must be static."); m.setAccessible(true); return m; }
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { Object obj = null; if (CLOSE_METHOD_NAME.equals(m.getName())) { SimpleConnectionPool.pushConnectionBackToPool(this); } else { obj = m.invoke(m_originConnection, args); } lastAccessTime = System.currentTimeMillis(); return obj; }
// // Examine a single method to see if it raises SQLFeatureNotSupportedException. // private void vetMethod( Object candidate, Class iface, Method method, HashSet<String> unsupportedList, HashSet<String> notUnderstoodList) throws Exception { try { method.invoke(candidate, getNullArguments(method.getParameterTypes())); // it's ok for the method to succeed } catch (Throwable e) { if (!(e instanceof InvocationTargetException)) { recordUnexpectedError(candidate, iface, method, notUnderstoodList, e); } else { Throwable cause = e.getCause(); if (cause instanceof SQLFeatureNotSupportedException) { boolean isExcludable = isExcludable(method); if (!isExcludable) { StackTraceElement[] stack = cause.getStackTrace(); int i = 0; while (i < stack.length && !stack[i].getMethodName().equals("notImplemented")) { ++i; } while (i < stack.length && stack[i].getMethodName().equals("notImplemented")) { ++i; } if (i == stack.length) { // cause.printStackTrace(); } unsupportedList.add( candidate.getClass().getName() + ": " + method + "@" + (i == stack.length ? "no source" : cause.getStackTrace()[i])); } else { } } else if (cause instanceof SQLException) { // swallow other SQLExceptions, caused by bogus args } else if (cause instanceof NullPointerException) { // swallow other NPEs, caused by bogus args } else if (cause instanceof ArrayIndexOutOfBoundsException) { // swallow these, caused by bogus args } else { recordUnexpectedError(candidate, iface, method, notUnderstoodList, cause); } } } }
private void dumpStack(ThreadReference thread, boolean showPC) { // ### Check for these. // env.failure("Thread no longer exists."); // env.failure("Target VM must be in interrupted state."); // env.failure("Current thread isn't suspended."); // ### Should handle extremely long stack traces sensibly for user. List<StackFrame> stack = null; try { stack = thread.frames(); } catch (IncompatibleThreadStateException e) { env.failure("Thread is not suspended."); } // ### Fix this! // ### Previously mishandled cases where thread was not current. // ### Now, prints all of the stack regardless of current frame. int frameIndex = 0; // int frameIndex = context.getCurrentFrameIndex(); if (stack == null) { env.failure("Thread is not running (no stack)."); } else { OutputSink out = env.getOutputSink(); int nFrames = stack.size(); for (int i = frameIndex; i < nFrames; i++) { StackFrame frame = stack.get(i); Location loc = frame.location(); Method meth = loc.method(); out.print(" [" + (i + 1) + "] "); out.print(meth.declaringType().name()); out.print('.'); out.print(meth.name()); out.print(" ("); if (meth.isNative()) { out.print("native method"); } else if (loc.lineNumber() != -1) { try { out.print(loc.sourceName()); } catch (AbsentInformationException e) { out.print("<unknown>"); } out.print(':'); out.print(loc.lineNumber()); } out.print(')'); if (showPC) { long pc = loc.codeIndex(); if (pc != -1) { out.print(", pc = " + pc); } } out.println(); } out.show(); } }
private Method findPublicVoidMethod(Class<?> aClass, String methodName) { for (Method method : aClass.getDeclaredMethods()) { if (isPublic(method.getModifiers()) && method.getReturnType() == void.class && methodName.equals(method.getName())) { return method; } } return null; }
/** * Computes the set of emit methods in the Assembler for a given IA32 opcode. * * @param emitters the set of all emit methods * @param opcode the opcode being examined */ private static EmitterSet buildSetForOpcode(Method[] emitters, String opcode) { EmitterSet s = new EmitterSet(); for (int i = 0; i < emitters.length; i++) { Method m = emitters[i]; if (m.getName().startsWith("emit" + opcode + "_") || m.getName().equals("emit" + opcode)) { s.add(new EmitterDescriptor(m.getName(), m.getParameterTypes())); } } return s; }
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()); } }
@SuppressWarnings("unchecked") private void addMethods(List list, boolean isStatic) { int count = klass.getMethodCount(isStatic); for (int i = 0; i != count; ++i) { Method method = klass.getMethod(i, isStatic); if (!method.isHosted()) { MethodID mid = new MethodID(method.getOffset(), isStatic); ProxyMethod proxyMethod = new ProxyMethod(mid, method); list.add(proxyMethod); } } }
/** * This function instantiates an invariant class by using the <type>(PptSlice) constructor. * * @param theClass the invariant class to be instantiated * @param sl the PptSlice representing the variables about which an invariant is determined * @return an instance of the class in theClass if one can be constructed, else throw a * RuntimeException */ private static Invariant instantiateClass(Class<? extends Invariant> theClass, PptSlice sl) { try { Method get_proto = theClass.getMethod("get_proto", new Class<?>[] {}); Invariant proto = (/*@Prototype*/ Invariant) get_proto.invoke(null, new Object[] {}); Invariant inv = proto.instantiate(sl); return (inv); } catch (Exception e) { e.printStackTrace(System.out); throw new RuntimeException( "Error while instantiating invariant " + theClass.getName() + ": " + e.toString()); } }
/** * `使用反射机制调用方法` * * @param methodName Method name * @param obj Object holder of the method * @param paraType Array of parameter types * @param paraValue Array of parameters * @return Returned object of the method */ public static Object call(String methodName, Object obj, Class[] paraType, Object[] paraValue) { try { Class cls = obj.getClass(); Method method = cls.getDeclaredMethod(methodName, paraType); // invoke() returns the object returned by the // underlying method. // It returns null, if the underlying method returns void. return method.invoke(obj, paraValue); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
/** * This function returns the check_modified method from the class type provided. * * @param theClass the class in which to find the check_modified method * @return the check_modified method if it exists * @throws RuntimeException if check_modified does not exist. */ private static Method getCheckModified(Class<? extends Invariant> theClass) { Method[] methods = theClass.getMethods(); Method currentMethod; for (int i = 0; i < methods.length; i++) { currentMethod = methods[i]; if (currentMethod.getName().lastIndexOf("check_modified") != -1) { // Method should be called check_modified return currentMethod; } } throw new RuntimeException("Cannot find check_modified method"); }