private static void reregisterNativeMethodsForRestoredClass(@Nonnull Class<?> realClass) { Method registerNatives = null; try { registerNatives = realClass.getDeclaredMethod("registerNatives"); } catch (NoSuchMethodException ignore) { try { registerNatives = realClass.getDeclaredMethod("initIDs"); } catch (NoSuchMethodException ignored) { } // OK } if (registerNatives != null) { try { registerNatives.setAccessible(true); registerNatives.invoke(null); } catch (IllegalAccessException ignore) { } // won't happen catch (InvocationTargetException ignore) { } // shouldn't happen either } // OK, although another solution will be required for this particular class if it requires // natives to be explicitly registered again (not all do, such as java.lang.Float). }
/** Determine whether the current user has Windows administrator privileges. */ public static boolean isWinAdmin() { if (!isWinPlatform()) return false; // for (String group : new com.sun.security.auth.module.NTSystem().getGroupIDs()) { // if (group.equals("S-1-5-32-544")) return true; // "S-1-5-32-544" is a well-known // security identifier in Windows. If the current user has it then he/she/it is an // administrator. // } // return false; try { Class<?> ntsys = Class.forName("com.sun.security.auth.module.NTSystem"); if (ntsys != null) { Object groupObj = SystemUtils.invoke( ntsys.newInstance(), ntsys.getDeclaredMethod("getGroupIDs"), (Object[]) null); if (groupObj instanceof String[]) { for (String group : (String[]) groupObj) { if (group.equals("S-1-5-32-544")) return true; // "S-1-5-32-544" is a well-known security identifier in Windows. If the // current user has it then he/she/it is an administrator. } } } } catch (ReflectiveOperationException e) { System.err.println(e); } return false; }
// setHandler creates a Proxy object from the passed OSXAdapter and adds it as an // ApplicationListener public static void setHandler(OSXAdapter adapter) { try { Class applicationClass = Class.forName("com.apple.eawt.Application"); if (macOSXApplication == null) { macOSXApplication = applicationClass.getConstructor((Class[]) null).newInstance((Object[]) null); } Class applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener"); Method addListenerMethod = applicationClass.getDeclaredMethod( "addApplicationListener", new Class[] {applicationListenerClass}); // Create a proxy object around this handler that can be reflectively added as an Apple // ApplicationListener Object osxAdapterProxy = Proxy.newProxyInstance( OSXAdapter.class.getClassLoader(), new Class[] {applicationListenerClass}, adapter); addListenerMethod.invoke(macOSXApplication, new Object[] {osxAdapterProxy}); } catch (ClassNotFoundException cnfe) { System.err.println( "This version of Mac OS X does not support the Apple EAWT. ApplicationEvent handling has been disabled (" + cnfe + ")"); } catch ( Exception ex) { // Likely a NoSuchMethodException or an IllegalAccessException loading/invoking // eawt.Application methods System.err.println("Mac OS X Adapter could not talk to EAWT:"); ex.printStackTrace(); } }
/** * `使用反射机制调用方法` * * @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); } }
/** * Unsupported command line interface. * * @param args The command line parameters. */ public static void main(String[] args) throws Exception { if (args.length > 0 && args[0].equals("-Xjdb")) { String[] newargs = new String[args.length + 2]; Class<?> c = Class.forName("com.redhat.ceylon.langtools.tools.example.debug.tty.TTY"); Method method = c.getDeclaredMethod("main", new Class<?>[] {args.getClass()}); method.setAccessible(true); System.arraycopy(args, 1, newargs, 3, args.length - 1); newargs[0] = "-connect"; newargs[1] = "com.redhat.ceylon.langtools.jdi.CommandLineLaunch:options=-esa -ea:com.redhat.ceylon.langtools.tools..."; newargs[2] = "com.redhat.ceylon.langtools.tools.javac.Main"; method.invoke(null, new Object[] {newargs}); } else { System.exit(compile(args)); } }
private Method findParamsProvidingMethodInTestclassHierarchy( String methodName, Class<?> testClass) { Method provideMethod = null; Class<?> declaringClass = testClass; while (declaringClass.getSuperclass() != null) { try { provideMethod = declaringClass.getDeclaredMethod(methodName); break; } catch (Exception e) { } declaringClass = declaringClass.getSuperclass(); } if (provideMethod == null) throw new RuntimeException( "Could not find method: " + methodName + " so no params were used."); return provideMethod; }
/** * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null. 匹配函数名+参数类型。 * * <p>用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) */ public static Method getAccessibleMethod( final Object obj, final String methodName, final Class<?>... parameterTypes) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { try { Method method = searchType.getDeclaredMethod(methodName, parameterTypes); makeAccessible(method); return method; } catch (NoSuchMethodException e) { // Method不在当前类定义,继续向上转型 continue; // new add } } return null; }
public static Method getMethod(Class cl, String methodName, Class paramTypes[]) throws Exception { Method method = null; Exception firstException = null; do { try { method = cl.getDeclaredMethod(methodName, paramTypes); } catch (Exception e) { if (firstException == null) firstException = e; cl = cl.getSuperclass(); } } while (method == null && cl != null); if (method == null) throw firstException; method.setAccessible(true); return method; }
/** * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null. * * <p>用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) */ public static Method getAccessibleMethod( final Object obj, final String methodName, final Class<?>... parameterTypes) { // AssertUtil.notNull(obj, "object不能为空"); for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { Method method = superClass.getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); return method; } catch (NoSuchMethodException e) { // NOSONAR // Method不在当前类定义,继续向上转型 } } return null; }
public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine().trim()); Object o; // Solution starts here if (num < 1 || num > Math.pow(2, 30)) throw new Exception(); Solution ob = new Solution(); Class<?> c = Class.forName("Solution$Private"); Constructor<?> constructor = c.getDeclaredConstructor(Solution.class); constructor.setAccessible(true); o = constructor.newInstance(ob); Method m = c.getDeclaredMethod("powerof2", new Class[] {int.class}); m.setAccessible(true); String ans = (String) m.invoke(o, num); System.out.println(num + " is " + ans); // ends here System.out.println( "An instance of class: " + o.getClass().getSimpleName() + " has been created"); } // end of main
protected <T extends FluentPage> T initClass(Class<T> cls) { T page = null; try { Constructor construct = cls.getDeclaredConstructor(); construct.setAccessible(true); page = (T) construct.newInstance(); Class parent = Class.forName(Fluent.class.getName()); Method m = parent.getDeclaredMethod("setDriver", WebDriver.class); m.setAccessible(true); m.invoke(page, getDriver()); // init fields with default proxies Field[] fields = cls.getDeclaredFields(); for (Field fieldFromPage : fields) { if (!FluentWebElement.class.isAssignableFrom(fieldFromPage.getType())) { continue; } fieldFromPage.setAccessible(true); proxyElement(new DefaultElementLocatorFactory(getDriver()), page, fieldFromPage); } } catch (ClassNotFoundException e) { throw new ConstructionException( "Class " + (cls != null ? cls.getName() : " null") + "not found", e); } catch (IllegalAccessException e) { throw new ConstructionException( "IllegalAccessException on class " + (cls != null ? cls.getName() : " null"), e); } catch (NoSuchMethodException e) { throw new ConstructionException( "No constructor found on class " + (cls != null ? cls.getName() : " null"), e); } catch (InstantiationException e) { throw new ConstructionException( "Unable to instantiate " + (cls != null ? cls.getName() : " null"), e); } catch (InvocationTargetException e) { throw new ConstructionException( "Cannot invoke method setDriver on " + (cls != null ? cls.getName() : " null"), e); } return page; }
public Factory make(Class<?> cl) throws InstantiationException, IllegalAccessException { if (Factory.class.isAssignableFrom(cl)) return (cl.asSubclass(Factory.class).newInstance()); try { final Method mkm = cl.getDeclaredMethod("mkwidget", Widget.class, Object[].class); int mod = mkm.getModifiers(); if (Widget.class.isAssignableFrom(mkm.getReturnType()) && ((mod & Modifier.STATIC) != 0) && ((mod & Modifier.PUBLIC) != 0)) { return (new Factory() { public Widget create(Widget parent, Object[] args) { try { return ((Widget) mkm.invoke(null, parent, args)); } catch (Exception e) { if (e instanceof RuntimeException) throw ((RuntimeException) e); throw (new RuntimeException(e)); } } }); } } catch (NoSuchMethodException e) { } return (null); }
@SuppressWarnings("unchecked") LDAPObjectHandler(final Class<T> type) throws LDAPPersistException { this.type = type; final Class<? super T> superclassType = type.getSuperclass(); if (superclassType == null) { superclassHandler = null; } else { final LDAPObject superclassAnnotation = superclassType.getAnnotation(LDAPObject.class); if (superclassAnnotation == null) { superclassHandler = null; } else { superclassHandler = new LDAPObjectHandler(superclassType); } } final TreeMap<String, FieldInfo> fields = new TreeMap<String, FieldInfo>(); final TreeMap<String, GetterInfo> getters = new TreeMap<String, GetterInfo>(); final TreeMap<String, SetterInfo> setters = new TreeMap<String, SetterInfo>(); ldapObject = type.getAnnotation(LDAPObject.class); if (ldapObject == null) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_OBJECT_NOT_ANNOTATED.get(type.getName())); } final LinkedHashMap<String, String> objectClasses = new LinkedHashMap<String, String>(10); final String oc = ldapObject.structuralClass(); if (oc.length() == 0) { structuralClass = getUnqualifiedClassName(type); } else { structuralClass = oc; } final StringBuilder invalidReason = new StringBuilder(); if (PersistUtils.isValidLDAPName(structuralClass, invalidReason)) { objectClasses.put(toLowerCase(structuralClass), structuralClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_STRUCTURAL_CLASS.get( type.getName(), structuralClass, invalidReason.toString())); } auxiliaryClasses = ldapObject.auxiliaryClass(); for (final String auxiliaryClass : auxiliaryClasses) { if (PersistUtils.isValidLDAPName(auxiliaryClass, invalidReason)) { objectClasses.put(toLowerCase(auxiliaryClass), auxiliaryClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_AUXILIARY_CLASS.get( type.getName(), auxiliaryClass, invalidReason.toString())); } } superiorClasses = ldapObject.superiorClass(); for (final String superiorClass : superiorClasses) { if (PersistUtils.isValidLDAPName(superiorClass, invalidReason)) { objectClasses.put(toLowerCase(superiorClass), superiorClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_SUPERIOR_CLASS.get( type.getName(), superiorClass, invalidReason.toString())); } } if (superclassHandler != null) { for (final String s : superclassHandler.objectClassAttribute.getValues()) { objectClasses.put(toLowerCase(s), s); } } objectClassAttribute = new Attribute("objectClass", objectClasses.values()); final String parentDNStr = ldapObject.defaultParentDN(); try { defaultParentDN = new DN(parentDNStr); } catch (LDAPException le) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_DEFAULT_PARENT.get( type.getName(), parentDNStr, le.getMessage()), le); } final String postDecodeMethodName = ldapObject.postDecodeMethod(); if (postDecodeMethodName.length() > 0) { try { postDecodeMethod = type.getDeclaredMethod(postDecodeMethodName); postDecodeMethod.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_POST_DECODE_METHOD.get( type.getName(), postDecodeMethodName, getExceptionMessage(e)), e); } } else { postDecodeMethod = null; } final String postEncodeMethodName = ldapObject.postEncodeMethod(); if (postEncodeMethodName.length() > 0) { try { postEncodeMethod = type.getDeclaredMethod(postEncodeMethodName, Entry.class); postEncodeMethod.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_POST_ENCODE_METHOD.get( type.getName(), postEncodeMethodName, getExceptionMessage(e)), e); } } else { postEncodeMethod = null; } try { constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_NO_DEFAULT_CONSTRUCTOR.get(type.getName()), e); } Field tmpDNField = null; Field tmpEntryField = null; final LinkedList<FieldInfo> tmpRFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpAAFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpCAFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpRDNFields = new LinkedList<FieldInfo>(); for (final Field f : type.getDeclaredFields()) { final LDAPField fieldAnnotation = f.getAnnotation(LDAPField.class); final LDAPDNField dnFieldAnnotation = f.getAnnotation(LDAPDNField.class); final LDAPEntryField entryFieldAnnotation = f.getAnnotation(LDAPEntryField.class); if (fieldAnnotation != null) { f.setAccessible(true); final FieldInfo fieldInfo = new FieldInfo(f, type); final String attrName = toLowerCase(fieldInfo.getAttributeName()); if (fields.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), fieldInfo.getAttributeName())); } else { fields.put(attrName, fieldInfo); } switch (fieldInfo.getFilterUsage()) { case REQUIRED: tmpRFilterFields.add(fieldInfo); break; case ALWAYS_ALLOWED: tmpAAFilterFields.add(fieldInfo); break; case CONDITIONALLY_ALLOWED: tmpCAFilterFields.add(fieldInfo); break; case EXCLUDED: default: break; } if (fieldInfo.includeInRDN()) { tmpRDNFields.add(fieldInfo); } } if (dnFieldAnnotation != null) { f.setAccessible(true); if (fieldAnnotation != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get( type.getName(), "LDAPField", "LDAPDNField", f.getName())); } if (tmpDNField != null) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_MULTIPLE_DN_FIELDS.get(type.getName())); } final int modifiers = f.getModifiers(); if (Modifier.isFinal(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_DN_FIELD_FINAL.get(f.getName(), type.getName())); } else if (Modifier.isStatic(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_DN_FIELD_STATIC.get(f.getName(), type.getName())); } final Class<?> fieldType = f.getType(); if (fieldType.equals(String.class)) { tmpDNField = f; } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_DN_FIELD_TYPE.get( type.getName(), f.getName(), fieldType.getName())); } } if (entryFieldAnnotation != null) { f.setAccessible(true); if (fieldAnnotation != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get( type.getName(), "LDAPField", "LDAPEntryField", f.getName())); } if (tmpEntryField != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_MULTIPLE_ENTRY_FIELDS.get(type.getName())); } final int modifiers = f.getModifiers(); if (Modifier.isFinal(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ENTRY_FIELD_FINAL.get(f.getName(), type.getName())); } else if (Modifier.isStatic(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ENTRY_FIELD_STATIC.get(f.getName(), type.getName())); } final Class<?> fieldType = f.getType(); if (fieldType.equals(ReadOnlyEntry.class)) { tmpEntryField = f; } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_ENTRY_FIELD_TYPE.get( type.getName(), f.getName(), fieldType.getName())); } } } dnField = tmpDNField; entryField = tmpEntryField; requiredFilterFields = Collections.unmodifiableList(tmpRFilterFields); alwaysAllowedFilterFields = Collections.unmodifiableList(tmpAAFilterFields); conditionallyAllowedFilterFields = Collections.unmodifiableList(tmpCAFilterFields); rdnFields = Collections.unmodifiableList(tmpRDNFields); final LinkedList<GetterInfo> tmpRFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpAAFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpCAFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpRDNGetters = new LinkedList<GetterInfo>(); for (final Method m : type.getDeclaredMethods()) { final LDAPGetter getter = m.getAnnotation(LDAPGetter.class); final LDAPSetter setter = m.getAnnotation(LDAPSetter.class); if (getter != null) { m.setAccessible(true); if (setter != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_METHOD_ANNOTATIONS.get( type.getName(), "LDAPGetter", "LDAPSetter", m.getName())); } final GetterInfo methodInfo = new GetterInfo(m, type); final String attrName = toLowerCase(methodInfo.getAttributeName()); if (fields.containsKey(attrName) || getters.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName())); } else { getters.put(attrName, methodInfo); } switch (methodInfo.getFilterUsage()) { case REQUIRED: tmpRFilterGetters.add(methodInfo); break; case ALWAYS_ALLOWED: tmpAAFilterGetters.add(methodInfo); break; case CONDITIONALLY_ALLOWED: tmpCAFilterGetters.add(methodInfo); break; case EXCLUDED: default: // No action required. break; } if (methodInfo.includeInRDN()) { tmpRDNGetters.add(methodInfo); } } if (setter != null) { m.setAccessible(true); final SetterInfo methodInfo = new SetterInfo(m, type); final String attrName = toLowerCase(methodInfo.getAttributeName()); if (fields.containsKey(attrName) || setters.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName())); } else { setters.put(attrName, methodInfo); } } } requiredFilterGetters = Collections.unmodifiableList(tmpRFilterGetters); alwaysAllowedFilterGetters = Collections.unmodifiableList(tmpAAFilterGetters); conditionallyAllowedFilterGetters = Collections.unmodifiableList(tmpCAFilterGetters); rdnGetters = Collections.unmodifiableList(tmpRDNGetters); if (rdnFields.isEmpty() && rdnGetters.isEmpty()) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_NO_RDN_DEFINED.get(type.getName())); } fieldMap = Collections.unmodifiableMap(fields); getterMap = Collections.unmodifiableMap(getters); setterMap = Collections.unmodifiableMap(setters); final TreeSet<String> attrSet = new TreeSet<String>(); final TreeSet<String> lazySet = new TreeSet<String>(); if (ldapObject.requestAllAttributes()) { attrSet.add("*"); attrSet.add("+"); } else { for (final FieldInfo i : fields.values()) { if (i.lazilyLoad()) { lazySet.add(i.getAttributeName()); } else { attrSet.add(i.getAttributeName()); } } for (final SetterInfo i : setters.values()) { attrSet.add(i.getAttributeName()); } } attributesToRequest = new String[attrSet.size()]; attrSet.toArray(attributesToRequest); lazilyLoadedAttributes = new String[lazySet.size()]; lazySet.toArray(lazilyLoadedAttributes); }
public StructDef(Class c, String path, org.omg.CORBA.Container _defined_in, org.omg.CORBA.Repository ir) { def_kind = org.omg.CORBA.DefinitionKind.dk_Struct; containing_repository = ir; defined_in = _defined_in; this.path = path; Debug.assert( defined_in != null, "defined_in = null"); Debug.assert( containing_repository != null, "containing_repository = null"); try { String classId = c.getName(); myClass = c; version( "1.0" ); full_name = classId.replace('.', '/'); if( classId.indexOf('.') > 0 ) { name( classId.substring( classId.lastIndexOf('.')+1 ) ); absolute_name = org.omg.CORBA.ContainedHelper.narrow( defined_in ).absolute_name() + "::" + name; } else { name( classId ); absolute_name = "::" + name; } helperClass = RepositoryImpl.loader.loadClass( classId + "Helper") ; id( (String)helperClass.getDeclaredMethod( "id", null ).invoke( null, null )); type = TypeCodeUtil.getTypeCode( myClass, RepositoryImpl.loader, null, classId ); members = new org.omg.CORBA.StructMember[ type.member_count() ]; for( int i = 0; i < members.length; i++ ) { org.omg.CORBA.TypeCode type_code = type.member_type(i); String member_name = type.member_name(i); members[i] = new org.omg.CORBA.StructMember( member_name, type_code, null ); } /* get directory for nested definitions' classes */ File f = new File( path + fileSeparator + classId.replace('.', fileSeparator) + "Package" ); if( f.exists() && f.isDirectory() ) my_dir = f; org.jacorb.util.Debug.output(2, "StructDef: " + absolute_name ); } catch ( Exception e ) { e.printStackTrace(); throw new org.omg.CORBA.INTF_REPOS( ErrorMsg.IR_Not_Implemented, org.omg.CORBA.CompletionStatus.COMPLETED_NO); } }
/** * Find main method in class. * * @param c main class * @return main method in class, if it exists * @throws NoSuchMethodException if class does not contain a main method */ private Method findMain(Class c) throws NoSuchMethodException { return c.getDeclaredMethod("main", new Class[] {String[].class}); }