private static void initFields(Class<?> clazz) { Field[] srcFields = clazz.getDeclaredFields(); for (Field field : srcFields) { Log.d(TAG, "modify " + clazz.getName() + "." + field.getName() + " flag:"); setFieldFlag(field); } }
@Override public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { if (ex == null) { return; } if (excludedExceptions.contains(ex.getClass())) { return; } for (Class<? extends Exception> excludedException : excludedExceptions) { if (excludedException.isInstance(ex)) { return; } } if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Logger controllerLogger = Logger.getLogger(handlerMethod.getBeanType()); controllerLogger.error(String.format("uncaught exception from %s", handlerMethod), ex); } else { logger.error( String.format("uncaught exception from a handler of unknown type: %s", handler), ex); } }
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException { AnnotationMetadata metadata = configClass.getMetadata(); if (this.environment != null && ProfileHelper.isProfileAnnotationPresent(metadata)) { if (!this.environment.acceptsProfiles(ProfileHelper.getCandidateProfiles(metadata))) { return; } } while (metadata != null) { doProcessConfigurationClass(configClass, metadata); String superClassName = metadata.getSuperClassName(); if (superClassName != null && !Object.class.getName().equals(superClassName)) { if (metadata instanceof StandardAnnotationMetadata) { Class<?> clazz = ((StandardAnnotationMetadata) metadata).getIntrospectedClass(); metadata = new StandardAnnotationMetadata(clazz.getSuperclass()); } else { MetadataReader reader = this.metadataReaderFactory.getMetadataReader(superClassName); metadata = reader.getAnnotationMetadata(); } } else { metadata = null; } } if (this.configurationClasses.contains(configClass) && configClass.getBeanName() != null) { // Explicit bean definition found, probably replacing an import. // Let's remove the old one and go with the new one. this.configurationClasses.remove(configClass); } this.configurationClasses.add(configClass); }
private static void checkMongoClient( Configuration configuration, Class<?> mappedClass, String clientName, String dbName) { Configuration mongodbClientConfiguration = getMongoClientConfiguration(configuration, clientName); if (mongodbClientConfiguration.isEmpty()) { throw SeedException.createNew(MongoDbErrorCodes.UNKNOWN_CLIENT_SPECIFIED) .put("aggregate", mappedClass.getName()) .put("clientName", clientName) .put("dbName", dbName); } boolean async = mongodbClientConfiguration.getBoolean("async", false); if (async) { throw SeedException.createNew(MorphiaErrorCodes.ERROR_ASYNC_CLIENT) .put("aggregate", mappedClass.getName()) .put("clientName", clientName) .put("dbName", dbName); } String[] dbNames = mongodbClientConfiguration.getStringArray("databases"); boolean found = false; for (String nameToCheck : dbNames) { if (nameToCheck.equals(resolveDatabaseAlias(mongodbClientConfiguration, dbName))) { found = true; break; } } if (!found) { throw SeedException.createNew(MorphiaErrorCodes.UNKNOW_DATABASE_NAME) .put("aggregate", mappedClass.getName()) .put("clientName", clientName) .put("dbName", dbName); } }
private static RetryPolicy instantiateRetryPolicy( String policyClassName, Object[] args, String raw) throws Exception { Class<?> policyClass = Class.forName(policyClassName); for (Constructor<?> con : policyClass.getConstructors()) { Class<?>[] parameterClasses = con.getParameterTypes(); if (args.length == parameterClasses.length) { boolean allInts = true; for (Class<?> pc : parameterClasses) { if (!pc.equals(int.class)) { allInts = false; break; } } if (!allInts) { break; } log.debug("About to instantiate class {} with {} arguments", con.toString(), args.length); return (RetryPolicy) con.newInstance(args); } } throw new Exception( "Failed to identify a class matching the Astyanax Retry Policy config string \"" + raw + "\""); }
public <T extends AbstractTask> T createTask(Class<T> type, Project project, String name) { Task task = TASK_FACTORY.createTask( (ProjectInternal) project, GUtil.map(Task.TASK_TYPE, type, Task.TASK_NAME, name)); assertTrue(type.isAssignableFrom(task.getClass())); return type.cast(task); }
public static boolean isValidResourceClass(Class<?> c) { if (c.isInterface() || Modifier.isAbstract(c.getModifiers())) { LOG.info("Ignoring invalid resource class " + c.getName()); return false; } return true; }
public static void main(String[] args) throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); System.out.println("" + ToolProvider.getSystemJavaCompiler()); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); StringObject so = new StringObject( "CalculatorTest", "class CalculatorTest {" + " public int multiply(int multiplicand, int multiplier) {" + " System.out.println(multiplicand);" + " System.out.println(multiplier);" + " return multiplicand * multiplier;" + " }" + "}"); JavaFileObject file = so; Iterable files = Arrays.asList(file); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, files); Boolean result = task.call(); System.out.println(result); if (result) { Class clazz = Class.forName("CalculatorTest"); Object instance = clazz.newInstance(); Method m = clazz.getMethod("multiply", new Class[] {int.class, int.class}); Object[] o = new Object[] {3, 2}; System.out.println(m.invoke(instance, o)); } }
@Test public void should_Install_AWT_Event_Handler() { Class<CorrectEventHandler> exceptionHandlerType = CorrectEventHandler.class; AWTExceptionHandlerInstaller.installAWTExceptionHandler(exceptionHandlerType, writer); verify(writer) .updateSystemProperty("sun.awt.exception.handler", exceptionHandlerType.getName()); }
public String printParantClass(final Class c) { if (c == null) { return ""; } else { return printParantClass(c.getSuperclass()) + c.getName() + "\n"; } }
private Retriever(Retriever retriever, Class class1, Message message) { if (com / google / protobuf / Message.isAssignableFrom(class1) && !class1.isInstance(message)) { throw new IllegalArgumentException( (new StringBuilder()) .append("Bad messageDefaultInstance for ") .append(class1.getName()) .toString()); } descriptorRetriever = retriever; singularType = class1; messageDefaultInstance = message; if (com / google / protobuf / ProtocolMessageEnum.isAssignableFrom(class1)) { enumValueOf = GeneratedMessage.access$1300( class1, "valueOf", new Class[] {com / google / protobuf / Descriptors$EnumValueDescriptor}); enumGetValueDescriptor = GeneratedMessage.access$1300(class1, "getValueDescriptor", new Class[0]); return; } else { enumValueOf = null; enumGetValueDescriptor = null; return; } }
public SearchableCacheConfiguration( Class<?>[] classArray, Properties properties, EmbeddedCacheManager uninitializedCacheManager, ComponentRegistry cr) { this.providedServices = initializeProvidedServices(uninitializedCacheManager, cr); if (properties == null) { this.properties = new Properties(); } else { this.properties = rescopeProperties(properties); } classes = new HashMap<String, Class<?>>(); for (Class<?> c : classArray) { String classname = c.getName(); classes.put(classname, c); } // deal with programmatic mapping: searchMapping = SearchMappingBuilder.getSearchMapping(this); // if we have a SearchMapping then we can predict at least those entities specified in the // mapping // and avoid further SearchFactory rebuilds triggered by new entity discovery during cache // events if (searchMapping != null) { Set<Class<?>> mappedEntities = searchMapping.getMappedEntities(); for (Class<?> entity : mappedEntities) { classes.put(entity.getName(), entity); } } }
private File generateSaveFolder(Class<?> c) throws IOException { if (!INexObject.class.isAssignableFrom(c)) { return null; } String mediaFolder = Settings.MediaFolder().get(); String folder = "unknown"; if (c.getAnnotation(FileDetails.class) != null) { folder = c.getAnnotation(FileDetails.class).folder(); } if (!mediaFolder.endsWith(dir_sep)) mediaFolder = mediaFolder.concat(dir_sep); if (folder.startsWith(dir_sep)) folder = folder.substring(1); if (!folder.endsWith(dir_sep)) folder = folder.concat(dir_sep); if (folder.equals("unknown\\")) { return null; } File f = new File(mediaFolder + folder); f.mkdirs(); return f; }
protected void retrieveClassModelStructure() { this.classHandleName = objectClassModel.getAnnotation(ObjectClass.class).name(); fields = objectClassModel.getDeclaredFields(); Map<Class, Coder> tmpMapCoder = new HashMap<Class, Coder>(); Coder coderTmp = null; try { for (Field f : fields) { if (f.isAnnotationPresent(Attribute.class)) { coderTmp = tmpMapCoder.get(f.getAnnotation(Attribute.class).coder()); if (coderTmp == null) { coderTmp = f.getAnnotation(Attribute.class).coder().newInstance(); tmpMapCoder.put(f.getAnnotation(Attribute.class).coder(), coderTmp); } matchingObjectCoderIsValid(f, coderTmp); mapFieldCoder.put(f.getAnnotation(Attribute.class).name(), coderTmp); } } } catch (InstantiationException | IllegalAccessException e) { logger.error("Error in retreving the annotations of the fields"); e.printStackTrace(); } finally { tmpMapCoder = null; coderTmp = null; } }
private <T> String toClassString(Collection<Class<? extends T>> providers) { StringBuilder sb = new StringBuilder(); for (Class<?> provider : providers) { sb.append(provider.getName()).append(", "); } return sb.subSequence(0, sb.length() - 2).toString(); }
@SuppressWarnings("unchecked") CustomAuthenticationProviderImpl(HiveConf conf) throws AuthenticationException { this.customHandlerClass = (Class<? extends PasswdAuthenticationProvider>) conf.getClass( HiveConf.ConfVars.HIVE_SERVER2_CUSTOM_AUTHENTICATION_CLASS.varname, PasswdAuthenticationProvider.class); // Try initializing the class with non-default and default constructors try { this.customProvider = customHandlerClass.getConstructor(HiveConf.class).newInstance(conf); } catch (NoSuchMethodException e) { try { this.customProvider = customHandlerClass.getConstructor().newInstance(); // in java6, these four extend directly from Exception. So have to handle separately. In // java7, // the common subclass is ReflectiveOperationException } catch (NoSuchMethodException e1) { throw new AuthenticationException( "Can't instantiate custom authentication provider class. " + "Either provide a constructor with HiveConf as argument or a default constructor.", e); } catch (Exception e1) { throw new AuthenticationException(e.getMessage(), e); } } catch (Exception e) { throw new AuthenticationException(e.getMessage(), e); } }
/** * 遍历项目导入所有的Router * * @throws UnsupportedEncodingException * @throws RouterException */ public static void loadRouter() throws RouterException { try { List<String> classNames = PackageUtil.getClassName("model.controller"); for (String className : classNames) { System.out.println(classNames); Class clazz = Class.forName(className); if (!clazz.isAnnotationPresent(Controller.class)) // 只有有Controller注解的类才处理 continue; /** 遍历类下的方法 */ Method[] methods = clazz.getMethods(); for (Method method : methods) { if (!method.isAnnotationPresent(RequestMapping.class)) // 只有有RequestMapping的方法才生成router continue; Annotation annotation = method.getAnnotation(RequestMapping.class); Action action = new Action(); action.setActionPath(((RequestMapping) annotation).value()); action.setController(clazz.newInstance()); action.setMethod(method); addRouter(action); } } } catch (ClassNotFoundException e) { throw (new RouterException(e)); } catch (InstantiationException e) { throw (new RouterException(e)); } catch (IllegalAccessException e) { throw (new RouterException(e)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block throw (new RouterException(e)); } }
public String getUserNameFull() { String s = "Это Линокс"; if (isOSWindows()) { String className = "com.sun.security.auth.module.NTSystem"; try { ClassLoader cL = ClassLoader.getSystemClassLoader(); Class cls = cL.loadClass(className); Object obj = cls.newInstance(); Method methodGetName = cls.getDeclaredMethod("getName"); s = (String) methodGetName.invoke(obj); Method methodGetDomain = cls.getDeclaredMethod("getDomain"); s = (String) methodGetDomain.invoke(obj) + "\\" + s; } catch (ClassNotFoundException e) { return "undefined"; } catch (InstantiationException e) { return "undefined"; } catch (IllegalAccessException e) { return "undefined"; } catch (NoSuchMethodException e) { return "undefined"; } catch (InvocationTargetException e) { return "undefined"; } } return s; }
public static Method findPreDestroyMethod(Class<?> c, String name) { if (Object.class == c || null == c) { return null; } for (Method m : c.getDeclaredMethods()) { if (name != null) { if (m.getName().equals(name)) { return m; } } else if (m.getAnnotation(PreDestroy.class) != null) { return m; } } Method m = findPreDestroyMethod(c.getSuperclass(), name); if (m != null) { return m; } for (Class<?> i : c.getInterfaces()) { m = findPreDestroyMethod(i, name); if (m != null) { return m; } } return null; }
@SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> adapter) { if (adapter.equals(IUndoContext.class)) { return (T) undoContext; } if (adapter.equals(IProgressMonitor.class)) { if (progressDialog != null) { return (T) progressDialog.getProgressMonitor(); } } if (site != null) { if (adapter.equals(Shell.class)) { return (T) getWorkbenchWindow().getShell(); } if (adapter.equals(IWorkbenchWindow.class)) { return (T) getWorkbenchWindow(); } if (adapter.equals(IWorkbenchPart.class)) { return (T) site.getPart(); } // Refer all other requests to the part itself. // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=108144 IWorkbenchPart part = site.getPart(); if (part != null) { return Adapters.adapt(part, adapter); } } return null; }
/** * Returns an instance of the annotation MorphiaDatastore if the morphia configuration is ok. * * @param application Application * @param morphiaClass persistent morphia object * @return MorphiaDatastore */ public static MorphiaDatastore getMongoDatastore(Application application, Class<?> morphiaClass) { Configuration morphiaEntityConfiguration = application.getConfiguration(morphiaClass).subset("morphia"); if (morphiaEntityConfiguration.isEmpty()) { throw SeedException.createNew(MorphiaErrorCodes.UNKNOW_DATASTORE_CONFIGURATION) .put("aggregate", morphiaClass.getName()); } String clientName = morphiaEntityConfiguration.getString("clientName"); if (clientName == null) { throw SeedException.createNew(MorphiaErrorCodes.UNKNOW_DATASTORE_CLIENT) .put("aggregate", morphiaClass.getName()); } String dbName = morphiaEntityConfiguration.getString("dbName"); if (dbName == null) { throw SeedException.createNew(MorphiaErrorCodes.UNKNOW_DATASTORE_DATABASE) .put("aggregate", morphiaClass.getName()) .put("clientName", clientName); } checkMongoClient(application.getConfiguration(), morphiaClass, clientName, dbName); return new MorphiaDatastoreImpl(clientName, dbName); }
/** * Get the protocol name. If the protocol class has a ProtocolAnnotation, then get the protocol * name from the annotation; otherwise the class name is the protocol name. */ public static String getProtocolName(Class<?> protocol) { if (protocol == null) { return null; } ProtocolInfo anno = protocol.getAnnotation(ProtocolInfo.class); return (anno == null) ? protocol.getName() : anno.protocolName(); }
public static void main(String[] args) throws Exception { Do_Not_Terminate.forbidExit(); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine().trim()); Object o; // Must be used to hold the reference of the instance of // the class Solution.Inner.Private Inner in = new Inner(); o = in.new Private(); Class<?> clz = Class.forName(Solution3.class.getName() + "$Inner$Private"); for (Method m : clz.getDeclaredMethods()) { if (m.getName().indexOf("powerof2") > -1) { m.setAccessible(true); System.out.println(num + " is " + m.invoke(o, num)); } } // TODO System.out.println( "An instance of class: " + o.getClass().getCanonicalName() + " has been created"); } // end of try catch (Do_Not_Terminate.ExitTrappedException e) { System.out.println("Unsuccessful Termination!!"); } } // end of main
private static Class<?> getClassObject(Object o) throws ClassNotFoundException { if (o == null) { System.out.println("null"); } // 基本データ型の場合 if (o instanceof Boolean) { return boolean.class; } else if (o instanceof Integer) { return int.class; } else if (o instanceof Double) { return double.class; } else if (o instanceof Long) { return long.class; } else if (o instanceof Short) { return short.class; } else if (o instanceof Character) { return char.class; } else if (o instanceof Byte) { return byte.class; } else if (o instanceof Float) { return float.class; } // 基本データ型以外の場合:forName()でクラスオブジェクトを取得 else { System.out.println(Class.forName(strip(o.getClass().toString(), "class "))); return Class.forName(strip(o.getClass().toString(), "class ")); } }
/** * Creates the service under test and attaches all injected dependencies (Context, Application) to * it. This is called automatically by {@link #startService} or by {@link #bindService}. If you * need to call {@link AndroidTestCase#setContext(Context) setContext()} or {@link #setApplication * setApplication()}, do so before calling this method. */ protected void setupService() { mService = null; try { mService = mServiceClass.newInstance(); } catch (Exception e) { assertNotNull(mService); } if (getApplication() == null) { setupApplication(); } assertNotNull(mApplication); mService.attach( getContext(), null, // ActivityThread not actually used in Service mServiceClass.getName(), null, // token not needed when not talking with the // activity manager getApplication(), null // mocked services don't talk with the activity manager ); assertNotNull(mService); mServiceId = new Random().nextInt(); mServiceAttached = true; }
@Test(timeout = 1000) public void testGenerator() throws Exception { // load the resource ResourceSet set = this.resourceSetProvider.get(); URI uri = URI.createURI("res/Test0139_LineBreakInString.c"); Resource resource = set.getResource(uri, true); // validate the resource List<Issue> list = this.validator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl); Assert.assertTrue(list.isEmpty()); // configure and start the generator this.fileAccessSystem.setOutputPath("bin"); final Class<?> clazz = this.generator.getClass(); try { final Method method = clazz.getMethod("setFileName", String.class); if (method != null) { method.invoke(this.generator, "Test0139_LineBreakInString.c.i"); } } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // do nothing } this.generator.doGenerate(resource, this.fileAccessSystem); final String actual = this.getTextFromFile("bin/Test0139_LineBreakInString.c.i"); final String expected = this.getTextFromFile("expected/Test0139_LineBreakInString.c"); Assert.assertEquals(preprocess(expected), preprocess(actual)); }
protected WebDriver createInstanceOf(String className) { try { DesiredCapabilities capabilities = createCommonCapabilities(); capabilities.setJavascriptEnabled(true); capabilities.setCapability(TAKES_SCREENSHOT, true); capabilities.setCapability(ACCEPT_SSL_CERTS, true); capabilities.setCapability(SUPPORTS_ALERTS, true); if (isPhantomjs()) { capabilities.setCapability( "phantomjs.cli.args", // PhantomJSDriverService.PHANTOMJS_CLI_ARGS == // "phantomjs.cli.args" new String[] {"--web-security=no", "--ignore-ssl-errors=yes"}); } Class<?> clazz = Class.forName(className); if (WebDriverProvider.class.isAssignableFrom(clazz)) { return ((WebDriverProvider) clazz.newInstance()).createDriver(capabilities); } else { Constructor<?> constructor = Class.forName(className).getConstructor(Capabilities.class); return (WebDriver) constructor.newInstance(capabilities); } } catch (InvocationTargetException e) { throw runtime(e.getTargetException()); } catch (Exception invalidClassName) { throw new IllegalArgumentException(invalidClassName); } }
private <T> void verifySameImplementation( Class<T> serviceClass, Collection<Class<? extends T>> providers) { boolean providersAreTheSame = false; Class<?> firstProvider = null; for (Class<?> provider : providers) { if (firstProvider == null) { // set the class to match firstProvider = provider; continue; } if (firstProvider == provider) { providersAreTheSame = true; } else { throw new IllegalStateException( "More then one implementation found for " + serviceClass.getName() + ", " + "please check your classpath. The found implementations are " + toClassString(providers)); } } if (providersAreTheSame) { logger.warning( "More then one reference to the same implementation was found for " + serviceClass.getName() + ", please verify you classpath"); } }
public static UnrecognizedPropertyException from( JsonParser jsonParser, Object obj, String str, Collection<Object> collection) { if (obj == null) { throw new IllegalArgumentException(); } Class cls; if (obj instanceof Class) { cls = (Class) obj; } else { cls = obj.getClass(); } UnrecognizedPropertyException unrecognizedPropertyException = new UnrecognizedPropertyException( "Unrecognized field \"" + str + "\" (class " + cls.getName() + "), not marked as ignorable", jsonParser.getCurrentLocation(), cls, str, collection); unrecognizedPropertyException.prependPath(obj, str); return unrecognizedPropertyException; }
public static int getResourseIdByName(String packageName, String className, String name) { Class r = null; int id = 0; try { r = Class.forName(packageName + ".R"); Class[] classes = r.getClasses(); Class desireClass = null; for (int i = 0; i < classes.length; i++) { if (classes[i].getName().split("\\$")[1].equals(className)) { desireClass = classes[i]; break; } } if (desireClass != null) id = desireClass.getField(name).getInt(desireClass); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return id; }