List of usage examples for java.lang Class getDeclaredField
@CallerSensitive public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException
From source file:com.github.gekoh.yagen.api.DefaultNamingStrategy.java
@Override public String classToTableShortName(String className) { try {//from w ww . j av a2s. c o m Class<?> aClass = Class.forName(className); String tableShortName = null; if (aClass.isAnnotationPresent(Table.class)) { tableShortName = aClass.getAnnotation(Table.class).shortName(); } if (StringUtils.isEmpty(tableShortName)) { try { Field tblShortNameField = aClass.getDeclaredField("TABLE_NAME_SHORT"); if (tblShortNameField != null) { tableShortName = tblShortNameField.get(null).toString(); } } catch (Exception ignore) { } } if (StringUtils.isEmpty(tableShortName)) { tableShortName = tableShortNameFromTableName(classToTableName(className)); } return tableShortName(tableShortName); } catch (ClassNotFoundException e) { throw new IllegalStateException("cannot get table short name from class " + className, e); } }
From source file:org.jsonschema2pojo.integration.config.IncludeAccessorsIT.java
@Test public void beansOmitGettersAndSettersWhenAccessorsAreDisabled() throws ClassNotFoundException, SecurityException, NoSuchMethodException, NoSuchFieldException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile( "/schema/properties/primitiveProperties.json", "com.example", config("includeAccessors", false)); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); try {/*from ww w. ja va 2 s. c o m*/ generatedType.getDeclaredMethod("getA"); fail("Disabled accessors but getter was generated"); } catch (NoSuchMethodException e) { } try { generatedType.getDeclaredMethod("setA", Integer.class); fail("Disabled accessors but getter was generated"); } catch (NoSuchMethodException e) { } assertThat(generatedType.getDeclaredField("a").getModifiers(), is(Modifier.PUBLIC)); }
From source file:gov.nih.nci.iso21090.hibernate.tuple.IsoConstantTuplizerHelper.java
/** * Finds field in class by going to super class. * @param klass klass in which the filedName is to be searched * @param fieldName name of the field to be retrieved * @return Field or exception/*from w ww . j ava 2 s. c o m*/ */ @SuppressWarnings("PMD.EmptyCatchBlock") public Field findFieldInClass(Class klass, String fieldName) { Class tempKlass = klass; while (tempKlass != null && Object.class != tempKlass) { try { Field field = tempKlass.getDeclaredField(fieldName); if (field != null) { return field; } } catch (SecurityException e) { //No operation } catch (NoSuchFieldException e) { //No operation } tempKlass = tempKlass.getSuperclass(); } throw new HibernateException("No field found in class " + klass.getName() + " for " + fieldName); }
From source file:net.chaosserver.timelord.swingui.engine.BringToFrontThread.java
/** * Trigger an annoy by un-minimizing the window and bringing it to the * front./*from w w w . j a v a 2s . c om*/ */ protected void annoy() { lastAnnoy = System.currentTimeMillis(); getFrame().setExtendedState(Frame.NORMAL); getFrame().toFront(); getTimelord().showTodayTab(); // This bounces the Dock in Panther/Tiger try { Class<?> nsApplicationClass = Class.forName("com.apple.cocoa.application.NSApplication"); Method sharedAppMethod = nsApplicationClass.getDeclaredMethod("sharedApplication", new Class[] {}); Object nsApplicationObject = sharedAppMethod.invoke(null, new Object[] {}); Field userAttentionRequestCriticalField = nsApplicationClass .getDeclaredField("UserAttentionRequestCritical"); Method requestUserAttentionMethod = nsApplicationClass.getDeclaredMethod("requestUserAttention", new Class[] { userAttentionRequestCriticalField.getType() }); requestUserAttentionMethod.invoke(nsApplicationObject, new Object[] { userAttentionRequestCriticalField.get(null) }); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Issue bouncing dock", e); } } if (log.isTraceEnabled()) { log.trace("Bringing Window to Front"); } }
From source file:com.github.sakserv.minicluster.impl.KdcLocalCluster.java
protected void refreshDefaultRealm() throws Exception { // Config is statically initialized at this point. But the above configuration results in a different // initialization which causes the tests to fail. So the following two changes are required. // (1) Refresh Kerberos config. // refresh the config Class<?> configClass;/* w w w . j av a2s.c om*/ if (System.getProperty("java.vendor").contains("IBM")) { configClass = Class.forName("com.ibm.security.krb5.internal.Config"); } else { configClass = Class.forName("sun.security.krb5.Config"); } Method refreshMethod = configClass.getMethod("refresh", new Class[0]); refreshMethod.invoke(configClass, new Object[0]); // (2) Reset the default realm. try { Class<?> hadoopAuthClass = Class.forName("org.apache.hadoop.security.authentication.util.KerberosName"); Field defaultRealm = hadoopAuthClass.getDeclaredField("defaultRealm"); defaultRealm.setAccessible(true); defaultRealm.set(null, KerberosUtil.getDefaultRealm()); LOG.info("HADOOP: Using default realm " + KerberosUtil.getDefaultRealm()); } catch (ClassNotFoundException e) { // Don't care LOG.info( "Class org.apache.hadoop.security.authentication.util.KerberosName not found, Kerberos default realm not updated"); } try { Class<?> zookeeperAuthClass = Class.forName("org.apache.zookeeper.server.auth.KerberosName"); Field defaultRealm = zookeeperAuthClass.getDeclaredField("defaultRealm"); defaultRealm.setAccessible(true); defaultRealm.set(null, KerberosUtil.getDefaultRealm()); LOG.info("ZOOKEEPER: Using default realm " + KerberosUtil.getDefaultRealm()); } catch (ClassNotFoundException e) { // Don't care LOG.info( "Class org.apache.zookeeper.server.auth.KerberosName not found, Kerberos default realm not updated"); } }
From source file:org.suren.autotest.web.framework.data.ExcelDataSource.java
/** * ??/*from w ww . j ava2 s . c om*/ * @param row */ private void cellParse(Row row) { Class<?> targetCls = targetPage.getClass(); Cell nameCell = row.getCell(0); Cell dataCell = row.getCell(1); if (nameCell == null || dataCell == null) { return; } try { String fieldName = getStrFromCell(nameCell); if (StringUtils.isBlank(fieldName)) { return; } Field field = targetCls.getDeclaredField(fieldName); field.setAccessible(true); setValue(field, targetPage, getStrFromCell(dataCell)); } catch (NoSuchFieldException | SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
From source file:org.grails.orm.hibernate.SessionFactoryProxy.java
private void updateCurrentSessionContext(SessionFactory sessionFactory) { // patch the currentSessionContext variable of SessionFactoryImpl to use this proxy as the key CurrentSessionContext ssc = createCurrentSessionContext(); if (ssc instanceof GrailsSessionContext) { ((GrailsSessionContext) ssc).initJta(); }/*from w ww . j av a 2s . c o m*/ try { Class<? extends SessionFactory> sessionFactoryClass = sessionFactory.getClass(); Field currentSessionContextField = sessionFactoryClass.getDeclaredField("currentSessionContext"); if (currentSessionContextField != null) { ReflectionUtils.makeAccessible(currentSessionContextField); currentSessionContextField.set(sessionFactory, ssc); } } catch (NoSuchFieldException e) { // ignore } catch (SecurityException e) { // ignore } catch (IllegalArgumentException e) { // ignore } catch (IllegalAccessException e) { // ignore } }
From source file:com.bfd.harpc.config.ServerConfig.java
/** * ??iface//from w w w . j a v a 2 s . c om * <p> * * @return {@link Responder} */ @SuppressWarnings("rawtypes") protected Class reflectProtocolClass() { Class serviceClass = getRef().getClass(); Class<?>[] interfaces = serviceClass.getInterfaces(); if (interfaces.length == 0) { throw new RpcException("Service class should implements avro's interface!"); } // ?Responder for (Class clazz : interfaces) { try { clazz.getDeclaredField("PROTOCOL").get(null); return clazz; // return new SpecificResponder(clazz, ref); } catch (Exception e) { } } throw new RpcException("Service class should implements avro's interface!"); }
From source file:com.liferay.portal.configuration.ConfigurationImpl.java
public void addProperties(Properties properties) { try {//from w ww. j a v a 2s.com ComponentProperties componentProperties = _componentConfiguration.getProperties(); AggregatedProperties aggregatedProperties = (AggregatedProperties) componentProperties .toConfiguration(); Field field1 = CompositeConfiguration.class.getDeclaredField("configList"); field1.setAccessible(true); // Add to configList of base conf List<Configuration> configurations = (List<Configuration>) field1.get(aggregatedProperties); MapConfiguration newConfiguration = new MapConfiguration(properties); configurations.add(0, newConfiguration); // Add to configList of AggregatedProperties itself Class<?> clazz = aggregatedProperties.getClass(); Field field2 = clazz.getDeclaredField("baseConf"); field2.setAccessible(true); CompositeConfiguration compositeConfiguration = (CompositeConfiguration) field2 .get(aggregatedProperties); configurations = (List<Configuration>) field1.get(compositeConfiguration); configurations.add(0, newConfiguration); clearCache(); } catch (Exception e) { _log.error("The properties could not be added", e); } }
From source file:io.druid.guice.JsonConfigurator.java
public <T> T configurate(Properties props, String propertyPrefix, Class<T> clazz) throws ProvisionException { verifyClazzIsConfigurable(clazz);//w ww . ja v a 2 s . c o m // Make it end with a period so we only include properties with sub-object thingies. final String propertyBase = propertyPrefix.endsWith(".") ? propertyPrefix : propertyPrefix + "."; Map<String, Object> jsonMap = Maps.newHashMap(); for (String prop : props.stringPropertyNames()) { if (prop.startsWith(propertyBase)) { final String propValue = props.getProperty(prop); Object value; try { // If it's a String Jackson wants it to be quoted, so check if it's not an object or array and quote. String modifiedPropValue = propValue; if (!(modifiedPropValue.startsWith("[") || modifiedPropValue.startsWith("{"))) { modifiedPropValue = String.format("\"%s\"", modifiedPropValue); } value = jsonMapper.readValue(modifiedPropValue, Object.class); } catch (IOException e) { log.info(e, "Unable to parse [%s]=[%s] as a json object, using as is.", prop, propValue); value = propValue; } jsonMap.put(prop.substring(propertyBase.length()), value); } } final T config; try { config = jsonMapper.convertValue(jsonMap, clazz); } catch (IllegalArgumentException e) { throw new ProvisionException( String.format("Problem parsing object at prefix[%s]: %s.", propertyPrefix, e.getMessage()), e); } final Set<ConstraintViolation<T>> violations = validator.validate(config); if (!violations.isEmpty()) { List<String> messages = Lists.newArrayList(); for (ConstraintViolation<T> violation : violations) { String path = ""; try { Class<?> beanClazz = violation.getRootBeanClass(); final Iterator<Path.Node> iter = violation.getPropertyPath().iterator(); while (iter.hasNext()) { Path.Node next = iter.next(); if (next.getKind() == ElementKind.PROPERTY) { final String fieldName = next.getName(); final Field theField = beanClazz.getDeclaredField(fieldName); if (theField.getAnnotation(JacksonInject.class) != null) { path = String.format(" -- Injected field[%s] not bound!?", fieldName); break; } JsonProperty annotation = theField.getAnnotation(JsonProperty.class); final boolean noAnnotationValue = annotation == null || Strings.isNullOrEmpty(annotation.value()); final String pathPart = noAnnotationValue ? fieldName : annotation.value(); if (path.isEmpty()) { path += pathPart; } else { path += "." + pathPart; } } } } catch (NoSuchFieldException e) { throw Throwables.propagate(e); } messages.add(String.format("%s - %s", path, violation.getMessage())); } throw new ProvisionException(Iterables.transform(messages, new Function<String, Message>() { @Nullable @Override public Message apply(@Nullable String input) { return new Message(String.format("%s%s", propertyBase, input)); } })); } log.info("Loaded class[%s] from props[%s] as [%s]", clazz, propertyBase, config); return config; }