/** * We are allowing consumers of the SDK to register their own deriived classes from the base * models we have inside the SDK. This allows for cases where the consumer wants to add addtional * flags and functions to the model and yet have orginal parsed objects of his liking. Example * SFFile does not provide the isSynced flag. The consumer app can extend like : * * <p>SFFileEx extends SFFile <br> * { <br> * boolean mIsSync <br> * } * * @throws IllegalAccessException * @throws InstantiationException * @throws SFInvalidTypeException */ public static void registerSubClass(SFV3ElementType elementType, Class<?> newClass) throws InstantiationException, IllegalAccessException, SFInvalidTypeException { if (newClass == null) { throw new SFInvalidTypeException( " NULL does not extend " + elementType.mOriginalClass.toString()); } // test if the new class is a real extension of the type being replaced. if (!elementType.mOriginalClass.isInstance(newClass.newInstance())) { String msg = newClass.toString() + " does not extend " + elementType.mOriginalClass.toString(); Logger.d(TAG, msg); throw new SFInvalidTypeException(msg); } Logger.d( TAG, "Successfully registered : " + newClass.toString() + " to replace " + elementType.mOriginalClass.toString()); elementType.mOverrideClass = newClass; registerSubClass(elementType.mToString.replace(prefix, "").replace(suffix, ""), newClass); }
/** * オブジェクトのフィールドにデータを設定する<br> * Integer、Float、Float[]、Stringにしか対応していない * * @param obj 設定対象オブジェクト * @param fl 設定対象フィールド * @param ty 設定対象フィールドの型 * @param data 設定データ * @throws IllegalArgumentException * @throws IllegalAccessException */ protected void dataSetter(Object obj, Field fl, Class ty, String data) throws IllegalArgumentException, IllegalAccessException { // Integer型のデータを設定 if (ty.toString().equals("class java.lang.Integer")) { fl.set(obj, Integer.parseInt(data)); } // Float型のデータを設定 if (ty.toString().equals("class java.lang.Float")) { fl.set(obj, Float.parseFloat(data)); } // String型のデータを設定(""の内側) if (ty.toString().equals("class java.lang.String")) { fl.set(obj, getDoubleQuoatString(data)); } // Float[]型のデータを設定 if (ty.toString().equals("class [Ljava.lang.Float;")) { String[] s; s = data.split(" "); Float[] f = new Float[s.length]; for (int i = 0; i < s.length; i++) { f[i] = Float.parseFloat(s[i]); } fl.set(obj, f); } }
/** * Returns the {@link ComponentUI} for the specified {@link JComponent}. * * @param target the component for which the ComponentUI is requested * @return the {@link ComponentUI} for the specified {@link JComponent} */ public ComponentUI getUI(JComponent target) { String classId = target.getUIClassID(); Class cls = getUIClass(classId); if (cls == null) { getUIError("failed to locate UI class:" + classId); return null; } Method factory; try { factory = cls.getMethod("createUI", new Class[] {JComponent.class}); } catch (NoSuchMethodException nme) { getUIError("failed to locate createUI method on " + cls.toString()); return null; } try { return (ComponentUI) factory.invoke(null, new Object[] {target}); } catch (java.lang.reflect.InvocationTargetException ite) { getUIError( "InvocationTargetException (" + ite.getTargetException() + ") calling createUI(...) on " + cls.toString()); return null; } catch (Exception e) { getUIError("exception calling createUI(...) on " + cls.toString()); return null; } }
public static void registerSubClass(String originalClassName, Class<?> newClass) throws InstantiationException, IllegalAccessException, SFInvalidTypeException { if (newClass == null || originalClassName == null) { throw new SFInvalidTypeException(" NULL classes not allowed "); } Class originalClass = SFEntityTypeMap.getEntityTypeMap().get(originalClassName); if (originalClass == null) { throw new SFInvalidTypeException("Given Class does not exist"); } // test if the new class is a real extension of the type being replaced. if (!originalClass.isInstance(newClass.newInstance())) { String msg = newClass.toString() + " does not extend " + originalClass.toString(); Logger.d(TAG, msg); throw new SFInvalidTypeException(msg); } SFEntityTypeMap.getEntityTypeMap().put(originalClassName, newClass); SFDefaultGsonParser.routeSpecialClasses(originalClassName, newClass); Logger.d( TAG, "Successfully registered : " + newClass.toString() + " to replace " + originalClass.toString()); }
/** * Returns the RDFS Class URI for a model POJO class. The POJO class must contain a field named * 'RDFS_CLASS', and its value should be the class URI. * * @param clazz the Java class to extract the URI * @return the RDFS Class URI */ public static <T extends Resource> URI getUriOfClass(Class<T> clazz) { URI typeUri = null; try { typeUri = (URI) clazz.getDeclaredField("RDFS_CLASS").get(""); logger.debug("RDFS_CLASS is " + typeUri + " for class " + clazz.toString()); } catch (Exception e) { logger.error("RDFS_CLASS attribute is not defined for the class " + clazz.toString()); } return typeUri; }
/** * Get a {@link java.lang.reflect.Constructor Constructor} from a {@link java.lang.Class Class} * that you normally can't use. * * @param temp The {@link java.lang.Class Class} that you want to get the {@link * java.lang.reflect.Constructor Constructor} form. * @param parameters The parameters of the {@link java.lang.reflect.Constructor Constructor} that * you want to get. * @return The {@link java.lang.reflect.Constructor Constructor} that you requested and makes them * accessible. */ public static Constructor getConstructor(Class<?> temp, Class... parameters) { try { Constructor constructor = temp.getDeclaredConstructor(parameters); return constructor; } catch (NoSuchMethodException e) { Log.error("There is no constructor for the class : " + temp.toString() + " :"); return null; } catch (SecurityException e) { Log.error("you can not access the constructor of this class : " + temp.toString() + " :"); return null; } }
public static Method getMethod(Class<?> classObject, String methodName) { try { return classObject.getMethod(methodName, boolean.class); } catch (NoSuchMethodException e) { Log.i(K9.LOG_TAG, "Can't get method " + classObject.toString() + "." + methodName); } catch (Exception e) { Log.e( K9.LOG_TAG, "Error while using reflection to get method " + classObject.toString() + "." + methodName, e); } return null; }
public static void main(String args[]) { Elephant Nellie = new Elephant("Nellie"); LinkedList<String> nellieLikes = new LinkedList<String>(); // Try adding more than apples? nellieLikes.add("apples"); // nellieLikes.add( "elephants" ); Nellie.setLikes(nellieLikes); // What happens to the 'likes' print out if nellie likes more than one thing? System.out.println(Nellie.getName() + " likes " + Nellie.getLikes().getFirst()); System.out.println( Nellie.getName() + " is an instance of " + Nellie.getClass().getSuperclass()); // This just iterates through the superclasses of Nellie, working up the inheritance tree. Class cls = Nellie.getClass(); Class oldCls = cls; while ((cls = cls.getSuperclass()) != null) { if (cls.toString().equals("class java.lang.Object")) { System.out.println("And in Java, every Object is an instance of " + cls); } else { System.out.println(oldCls + " is an instance of: " + cls); } oldCls = cls; } }
private void setUsage(Class<?> optionHolderClass) { Usage newUsage = optionHolderClass.getAnnotation(Usage.class); if (newUsage == null) throw new XerialError(XerialErrorCode.NO_USAGE_ANNOTATION, optionHolderClass.toString()); if (usage == null) usage = newUsage; }
@Override protected void onResume() { super.onResume(); registerReceiver(receiver, new IntentFilter(service.toString())); updateItems(); }
public Object getAdapter(Class adapter) { AdapterDebug.print(this, adapter); if (adapter.equals(ILaunch.class)) { return target.getAdapter(adapter); } else if (adapter.equals(org.eclipse.debug.ui.actions.IRunToLineTarget.class)) { return this.target.getRunToLineTarget(); } else if (adapter.equals(IPropertySource.class) || adapter.equals(ITaskListResourceAdapter.class) || adapter.equals(org.eclipse.ui.IContributorResourceAdapter.class) || adapter.equals(org.eclipse.ui.IActionFilter.class) || adapter.equals(org.eclipse.ui.model.IWorkbenchAdapter.class) || adapter.equals(org.eclipse.debug.ui.actions.IToggleBreakpointsTarget.class) || adapter.equals(IResource.class) || adapter.equals(org.eclipse.core.resources.IFile.class)) return super.getAdapter(adapter); // ongoing, I do not fully understand all the interfaces they'd like me to support // so I print them out as errors if (adapter.equals(IDeferredWorkbenchAdapter.class)) { return new DeferredWorkbenchAdapter(this); } // cannot check for the actual interface because it may not be available on eclipse 3.2 (it's // only available // from 3.3 onwards... and this is only a hack for it to work with eclipse 3.4) if (adapter .toString() .endsWith( "org.eclipse.debug.internal.ui.viewers.model.provisional.IElementContentProvider")) { return new PyVariableContentProviderHack(); } AdapterDebug.printDontKnow(this, adapter); return super.getAdapter(adapter); }
public void toScreen(String s, Class module, String TYPE) { Color c = Color.BLACK; if (TYPE != null) { if (TYPE.contains("ERROR")) c = Color.RED; if (TYPE.contains("WARNING")) c = new Color(255, 106, 0); if (TYPE.contains("DEBUG")) c = Color.BLUE; if (module.toString().equalsIgnoreCase("Exception")) c = Color.RED; } StyleContext sc = StyleContext.getDefaultStyleContext(); javax.swing.text.AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); int len = SCREEN.getDocument().getLength(); // same value as SCREEN.setCaretPosition(len); // place caret at the end (with no selection) SCREEN.setCharacterAttributes(aset, false); SCREEN.replaceSelection( "[" + getData() + " - " + module.getSimpleName() + " - " + TYPE + "] " + s + "\n"); // there is no selection, so inserts at caret SCREEN.setFont(new Font("Monospaced", Font.PLAIN, 14)); aggiungiRiga(s, module, TYPE); }
/** * Erzeugt eine neue HerkuftsVariante (RassenVariante, KulturVariante oder ProfessionsVarianet). * VORSICHT: In dieser Methode wird (noch) NICHT die Variante beim Parent gesetzt. * * @param clazz Die Klasse der gewünschten zu erzeugenden Variante * @param parent Die Herkunft, von der die Variante abstammt * @return Eine neue Variante von "parent" vom typ "clazz" */ public CharElement buildHerkunftVariante(Class clazz, Herkunft parent) { CharElement charElem; // TODO Auch im parent muß die variante natürlich gesetzt werden - // entweder hier ober je nach GUI auch im Editor if (clazz == RasseVariante.class || clazz == Rasse.class) { charElem = new RasseVariante(); ((RasseVariante) charElem).setVarianteVon((Rasse) parent); ((RasseVariante) charElem).setAdditionsVariante(true); ((RasseVariante) charElem).setGeschwindigk(((Rasse) parent).getGeschwindigk()); } else if (clazz == KulturVariante.class || clazz == Kultur.class) { charElem = new KulturVariante(); ((KulturVariante) charElem).setVarianteVon((Kultur) parent); ((KulturVariante) charElem).setAdditionsVariante(true); } else if (clazz == ProfessionVariante.class || clazz == Profession.class) { charElem = new ProfessionVariante(); ((ProfessionVariante) charElem).setVarianteVon((Profession) parent); ((ProfessionVariante) charElem).setAdditionsVariante(true); ((ProfessionVariante) charElem).setAufwand(((Profession) parent).getAufwand()); } else { throw new IllegalArgumentException( "Keine Behandlung für ein Element des Typs " + clazz.toString() + " vorhanden."); } createCharElement(charElem); return charElem; }
public FunctionContainer() { functions = new HashMap<String, Method>(); numFunctions = 0; try { String fullClassName = this.getClass().getName(); Class<?> myClassName = Class.forName(fullClassName); Method[] methods = myClassName.getMethods(); if (methods.length > 0) { for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (m.getName().contains("function")) { Class<?>[] paramTypes = m.getParameterTypes(); if (paramTypes.length > 0) { Class<?> lastParamType = paramTypes[paramTypes.length - 1]; if (lastParamType.toString().equals("boolean")) { functions.put(m.getName(), m); } } } } numFunctions = functions.size(); } } catch (Exception e) { System.out.println(e); } }
/** 生成xml */ public static String generateXML(Object object) { Class cls_class = object.getClass(); String cls_str = cls_class.toString(); String objname = cls_str.substring(cls_str.lastIndexOf(".") + 1, cls_str.length()); // 得到类名称,包含前缀 StringBuffer xml = new StringBuffer(); // 重命名 objname = "ops_trade"; xml.append("<" + objname + ">"); Field[] fields = cls_class.getDeclaredFields(); // 得到成员属性名称,不包含前缀 String name = ""; try { for (int i = 0; i < fields.length; i++) { name = fields[i].getName(); if (name.equals("preTradeLot") || name.equals("preTrade")) { // 如果是序列号就去掉 continue; } Object objValue = PropertyUtils.getProperty(object, name); // 得到属性值 xml.append(getFieldValue(objValue, name)); } } catch (Exception e) { log.error("在" + object + "中没有找到属性名为" + name + "的方法...", e); } xml.append("</" + objname + ">"); return xml.toString(); }
public RemoteInterfaceDescriptor getRemoteDescriptor(Class type) { TypeDescriptor td = getDescriptor(type); RemoteInterfaceDescriptor result = td.getRemoteInterface(); if (result != null) { return result; } RemoteDescriptor desc; if (java.rmi.Remote.class.isAssignableFrom(type)) { if (type.isInterface()) { desc = new RemoteInterfaceDescriptor(type, this); } else { desc = new RemoteClassDescriptor(type, this); } desc.init(); } else { throw new IllegalArgumentException( "class " + type.toString() + " does not implement" + " java.rmi.Remote"); } result = desc.getRemoteInterface(); td.setRemoteInterface(result); return result; }
@SuppressWarnings("unchecked") public SimulationMaster( int numberOfEventEmitters, Class eventEmitterClass, ActorRef listener, int numberOfEvents, long demoId, int messageDelay) { logger.info( "Starting simulation with " + numberOfEventEmitters + " of " + eventEmitterClass + " Event Emitters -- " + eventEmitterClass.toString()); this.listener = listener; this.numberOfEventEmitters = numberOfEventEmitters; this.eventEmitterClass = eventEmitterClass; this.delay_between_trucks = messageDelay; this.numberOfEvents = numberOfEvents; eventEmitterRouter = this.getContext() .actorOf( Props.create(eventEmitterClass, numberOfEvents, demoId, messageDelay) .withRouter(new RoundRobinRouter(numberOfEventEmitters)), "eventEmitterRouter"); }
@SuppressWarnings("unchecked") public <S extends EJBObject> EntityEJBLocator<? extends S> narrowAsEntity(final Class<S> type) { if (type.isAssignableFrom(getViewType())) { return (EntityEJBLocator<? extends S>) this; } throw new ClassCastException(type.toString()); }
// taken from TCK facesResourceBundleResolverGetTypeTest public String getResourceBundleType() { FacesContext context = FacesContext.getCurrentInstance(); ELContext elContext = context.getELContext(); ELResolver elResolver = elContext.getELResolver(); Class type = elResolver.getType(elContext, null, "resourceBundle03"); return type.toString(); }
/** * Create a new instance of a class using a specific constructor or log the exception if the class * is not instanceable. This method will rethrow any exception as an unchecked {@link * RuntimeException}. * * @param <T> the type of the instance to create * @param cls the class which represents the type of the instance to create. * @param constructor the constructor to use. * @param args an array of the constructor arguments. * @return a new instance of the type given on the argument by using the specified constructor. */ public static <T> T createInstance(Class<T> cls, Constructor constructor, Object... args) { try { return (T) constructor.newInstance(args); } catch (Throwable t) { logger.error("Could not create bean instance of class" + cls.toString(), t); throw new RuntimeException(t); } }
/** * Create a new instance of a class or log the exception if the class is not instanceable. This * method will rethrow any exception as an unchecked {@link RuntimeException}. * * @param <T> * @param cls * @return a new instance of the type given in the argument. */ public static <T> T createInstance(Class<T> cls) { try { return cls.newInstance(); } catch (Throwable t) { logger.error("Could not create bean instance of class " + cls.toString(), t); throw new RuntimeException(t); } }
@Override public String toString() { if (typeParameters.size() > 0) { return clazz + "<...>"; } else { return clazz.toString(); } }
private <T extends View> T findView(Class<? extends View> clazz, int id) throws ViewNotFoundException { View view = getActivity().findViewById(id); if (view != null && view.getClass().isAssignableFrom(clazz)) { return (T) view; } log.error("Cannot find view of {} with id {}", clazz.toString(), id); throw new ViewNotFoundException(); }
public static <T> Object newInstance(Class<T> c, int n) { if (NyARRleLabelFragmentInfo.class.equals(c)) return new NyARRleLabelFragmentInfo[n]; else if (SquareStack.Item.class.equals(c)) return new SquareStack.Item[n]; else if (INyARSingleCameraSystemObserver.class.equals(c)) { return new INyARSingleCameraSystemObserver[n]; } else Window.alert("Creating array of size " + n + " of " + c.toString()); return null; }
/** * Removes a given configurable class from registered list. * * @param interfaze the interface type of configurable class. * @return returns the removed configigurabke class if it existed, otherwise returns null. */ @SuppressWarnings("unchecked") public static <T> T removeConfigClass(Class<T> interfaze) { Assertor.notNull(interfaze); if (!interfaze.isInterface()) { throw new JGentleRuntimeException(interfaze.toString() + " must be a interface."); } return (T) JGentle.configObjClassList.remove(interfaze); }
/** * Given a map between a string and an object of unknown type, attempt to retrieve what value is * mapped to from the specified string and validate that the actual type matches the specified * class. * * @return Null if the types do not match, or the value */ private static Object validateAndGet(Map<String, Object> m, String s, Class<?> c) throws MissingMappingException, UnexpectedTypeException { Object o = m.get(s); if (o == null) throw new MissingMappingException(s); if (!c.isAssignableFrom(o.getClass())) throw new UnexpectedTypeException(s, c.toString(), o.getClass().toString()); else return o; }
@Test public void testBeforeAddInterceptor() throws Exception { final TestClassLoader loader = getTestClassLoader(); final String javassistClassName = "com.navercorp.pinpoint.profiler.interceptor.bci.TestObject"; loader.addTransformer( javassistClassName, new TransformCallback() { @Override public byte[] doInTransform( Instrumentor instrumentContext, ClassLoader classLoader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException { try { logger.info("modify className:{} cl:{}", className, classLoader); InstrumentClass aClass = instrumentContext.getInstrumentClass( classLoader, javassistClassName, classfileBuffer); String methodName = "callA"; aClass .getDeclaredMethod(methodName) .addInterceptor( "com.navercorp.pinpoint.profiler.interceptor.TestBeforeInterceptor"); return aClass.toBytecode(); } catch (InstrumentException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage(), e); } } }); loader.initialize(); Class<?> testObjectClazz = loader.loadClass(javassistClassName); final String methodName = "callA"; logger.info("class:{}", testObjectClazz.toString()); final Object testObject = testObjectClazz.newInstance(); Method callA = testObjectClazz.getMethod(methodName); callA.invoke(testObject); Interceptor interceptor = getInterceptor(loader, 0); assertEqualsIntField(interceptor, "call", 1); assertEqualsObjectField( interceptor, "className", "com.navercorp.pinpoint.profiler.interceptor.bci.TestObject"); assertEqualsObjectField(interceptor, "methodName", methodName); assertEqualsObjectField(interceptor, "args", null); assertEqualsObjectField(interceptor, "target", testObject); }
@SuppressWarnings("unchecked") public <T> AbstractGrblSerializer<String, T> getSerializer(Class<T> targetClass) throws GkTechnicalException { for (AbstractGrblSerializer<?, ?> abstractGrblSerializer : lstSerializer) { if (abstractGrblSerializer.getTargetClass() == targetClass) { return (AbstractGrblSerializer<String, T>) abstractGrblSerializer; } } throw new GkTechnicalException("No serializer found for class " + targetClass.toString()); }
public static <T extends Exception> T findExceptionByClass(Exception e, Class<T> exceptionClass) { Exception exception = e; while (exception != null) { if (exception.getClass().toString().equals(exceptionClass.toString())) return exceptionClass.cast(exception); exception = (Exception) exception.getCause(); } return null; }
@Test public void testClass() { Class sampleclass = MainSampleListFragment.class; Class superclass = sampleclass.getSuperclass(); System.out.println(superclass.toString()); System.out.println(superclass.getSuperclass().toString()); if (superclass == Fragment.class) { assert true; } }