/** * すべてのメンバを表示する * * @param Class<?> c メンバを表示したいクラス型オブジェクト */ public static void printAllMembers(Class<?> c) { System.out.println("クラス: "); System.out.println(c); System.out.println("フィールド: "); Field[] declaredfields = c.getDeclaredFields(); Field[] fields = c.getFields(); ArrayList<Field> fieldList = new ArrayList<Field>(fields.length); for (int i = 0; i < fields.length; i++) { fieldList.add(fields[i]); } for (int i = 0; i < declaredfields.length; i++) { if (!fieldList.contains(declaredfields[i])) { fieldList.add(declaredfields[i]); } } Field[] allFields = new Field[fieldList.size()]; for (int i = 0; i < allFields.length; i++) { allFields[i] = fieldList.get(i); } printMembers(allFields); System.out.println("コンストラクタ: "); Constructor[] declaredconstructors = c.getDeclaredConstructors(); Constructor[] constructors = c.getConstructors(); ArrayList<Constructor> constructorList = new ArrayList<Constructor>(constructors.length); for (int i = 0; i < constructors.length; i++) { constructorList.add(constructors[i]); } for (int i = 0; i < declaredconstructors.length; i++) { if (!constructorList.contains(declaredconstructors[i])) { constructorList.add(declaredconstructors[i]); } } Constructor[] allConstructors = new Constructor[constructorList.size()]; for (int i = 0; i < allConstructors.length; i++) { allConstructors[i] = constructorList.get(i); } printMembers(allConstructors); System.out.println("メソッド: "); Method[] declaredmethods = c.getDeclaredMethods(); Method[] methods = c.getMethods(); ArrayList<Method> methodList = new ArrayList<Method>(methods.length); for (int i = 0; i < methods.length; i++) { methodList.add(methods[i]); } for (int i = 0; i < declaredmethods.length; i++) { if (!methodList.contains(declaredmethods[i])) { methodList.add(declaredmethods[i]); } } Method[] allMethods = new Method[methodList.size()]; for (int i = 0; i < allMethods.length; i++) { allMethods[i] = methodList.get(i); } printMembers(allMethods); }
public void getFields(Class klass) { int num = klass.getFields().length; // if(klass.getFields().length = null){ String length = "" + num; if (!length.isEmpty()) { textArea3.setText("The class has " + length + " fields"); } else { textArea3.setText("The class has no fields"); } }
static void printFieldNames(Object o) { Class c = o.getClass(); Field[] publicFields = c.getFields(); for (int i = 0; i < publicFields.length; i++) { String fieldName = publicFields[i].getName(); Class typeClass = publicFields[i].getType(); String fieldType = typeClass.getName(); System.out.println("Name: " + fieldName + ", Type: " + fieldType); } }
@Override public TypeUsage getField(String fieldName, boolean staticContext) { for (Field field : clazz.getFields()) { if (field.getName().equals(fieldName)) { if (Modifier.isStatic(field.getModifiers()) == staticContext) { return ReflectionTypeDefinitionFactory.toTypeUsage(field.getType()); } } } throw new UnsupportedOperationException(); }
protected Field[] getFields() { if (fields == null) { Object object = getObject(); if (object != null) { Class theClass = object.getClass(); fields = theClass.getFields(); } } return fields; }
private static boolean testConvexPolygonArch() { boolean pass = true; int test = 1; int cnt; ConvexPolygon poly; Class cl; Class[] temp; System.out.println("ConvexPolygon architecture tests..."); Point a = new Point(7, 7); Point b = new Point(0, 9); Point c = new Point(-3, -5); Point d = new Point(2, -6); Point e = new Point(12, 0); Point[] vertices = new Point[5]; vertices[0] = new Point(a); vertices[1] = new Point(b); vertices[2] = new Point(c); vertices[3] = new Point(d); vertices[4] = new Point(e); poly = new ConvexPolygon(vertices, Color.cyan, false); cl = poly.getClass(); pass &= test(cl.getConstructors().length == 1, test++); pass &= test((temp = cl.getInterfaces()).length == 1, test++); pass &= test(temp[0].getName().equals("Shape"), test++); pass &= test(verifyEqualsMethodSignature(cl), test++); cnt = countModifiers(cl.getDeclaredMethods(), Modifier.PUBLIC); pass &= test(cnt == 9, test++); cnt = cl.getFields().length; pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED); pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE); pass &= test(cnt == 3, test++); // Count and test number of of PACKAGE fields cnt = cl.getDeclaredFields().length - countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE) - countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED) - countModifiers(cl.getDeclaredFields(), Modifier.PUBLIC); pass &= test(cnt == 0, test++); return pass; }
private static void vis(String name, Class type, Object value, String indent) throws Exception { if (value == null) { // nothing interesting to say prt(indent + name + ": null"); } else if (type.isPrimitive()) { // primitive if (type == Boolean.TYPE) prt(indent + name + ": " + ((Boolean) value).booleanValue()); else if (type == Character.TYPE) prt(indent + name + ": " + ((Character) value).charValue()); else if (type == Byte.TYPE) prt(indent + name + ": " + ((Byte) value).byteValue()); else if (type == Short.TYPE) prt(indent + name + ": " + ((Short) value).shortValue()); else if (type == Integer.TYPE) prt(indent + name + ": " + ((Integer) value).intValue()); else if (type == Long.TYPE) prt(indent + name + ": " + ((Long) value).longValue()); else if (type == Float.TYPE) prt(indent + name + ": " + ((Float) value).floatValue()); else if (type == Double.TYPE) prt(indent + name + ": " + ((Double) value).doubleValue()); else throw new IllegalArgumentException(); // NotReached } else if (type.isArray()) { // array Class componentType = type.getComponentType(); prt(indent + name + ": " + componentType.getName() + "[]"); for (int i = 0, n = Array.getLength(value); i < n; ++i) vis("" + i, componentType, Array.get(value, i), indent + " "); } else if (type.getName() .equals("java.lang.String")) { // treat frequently used type as special case prt(indent + name + ": \"" + (String) value + "\""); } else { // class (or interface) Field[] fields = type .getFields(); // !!note: Sun's jvm only returns *public* fields, jx returns *all* // fields if (fields.length == 0) { // no fields // prt(indent + name + ": declared as " + type.getName() + " actually is " + (value == null // ? "null" : value.getClass().getName()) + " self-described as \"" + value + "\""); prt( indent + name + ": declared as " + type.getName() + " actually is " + (value == null ? "null" : value.getClass().getName())); } else { // use fields to describe object prt(indent + name + ": " + type.getName()); for (int i = 0, n = fields.length; i < n; ++i) { Field f = fields[i]; if (Modifier.isStatic(f.getModifiers())) vis(f.getName(), f.getType(), f.get(value), indent + " static "); else vis(f.getName(), f.getType(), f.get(value), indent + " "); } } } }
public void background(int r, int g, int b) { Log.d("Pepper", "back " + r + ' ' + g + ' ' + b); canvas.drawARGB(255, r, g, b); Context c = App.self; Class cls = c.getClass(); Method[] methods = cls.getMethods(); Field[] fields = cls.getFields(); /* for (Method m : methods) { Log.d("Pepper", "method " + m.getName() + "; " + m); } for (Field f : fields) { Log.d("Pepper", "field " + f.getName()); } */ }
private void registerEvents() { Class<?> rootClass = NetworkCommand.class; Field[] fields = rootClass.getFields(); try { for (int i = 0; i < fields.length; i++) { if (fields[i].getType() == int.class) { fields[i].setAccessible(true); int value = fields[i].getInt(NetworkCommand.class); addEvent(value); // System.out.println("Registering event for: " + fields[i].getName() + ", value: " + // fields[i].getInt(NetworkCommand.class)); } } } catch (Exception e) { e.printStackTrace(); } }
private static boolean testTriangleArch() { boolean pass = true; int test = 1; int cnt; Triangle tri; Class cl; Class[] temp; System.out.println("Triangle architecture tests..."); Point a = new Point(0, 0); Point b = new Point(3, 0); Point c = new Point(0, 4); tri = new Triangle(a, b, c, Color.cyan, false); cl = tri.getClass(); pass &= test(cl.getConstructors().length == 1, test++); pass &= test((temp = cl.getInterfaces()).length == 1, test++); pass &= test(temp[0].getName().equals("Shape"), test++); pass &= test(verifyEqualsMethodSignature(cl), test++); cnt = countModifiers(cl.getDeclaredMethods(), Modifier.PUBLIC); pass &= test(cnt == 13, test++); cnt = cl.getFields().length; pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED); pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE); pass &= test(cnt == 5, test++); // Count and test number of of PACKAGE fields cnt = cl.getDeclaredFields().length - countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE) - countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED) - countModifiers(cl.getDeclaredFields(), Modifier.PUBLIC); pass &= test(cnt == 0, test++); return pass; }
private MutableTreeNode populateAttributes(CavityDBObject obj) { DefaultMutableTreeNode tree = new DefaultMutableTreeNode("attrs"); Class cls = obj.getClass(); for (Field f : cls.getFields()) { int mod = f.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) { String fieldName = f.getName(); try { Object value = f.get(obj); tree.add( new DefaultMutableTreeNode(String.format("%s=%s", fieldName, String.valueOf(value)))); } catch (IllegalAccessException e) { // do nothing. } } } return tree; }
public static void printFields(Class<?> c) { display2.append("フィールド\r\n"); Field[] declaredfields = c.getDeclaredFields(); Field[] fields = c.getFields(); ArrayList<Field> fieldList = new ArrayList<Field>(fields.length); for (int i = 0; i < fields.length; i++) { fieldList.add(fields[i]); } for (int i = 0; i < declaredfields.length; i++) { if (!fieldList.contains(declaredfields[i])) { fieldList.add(declaredfields[i]); } } Field[] allFields = new Field[fieldList.size()]; for (int i = 0; i < allFields.length; i++) { allFields[i] = fieldList.get(i); } printMembers(allFields); }
private static boolean testCircleArch() { boolean pass = true; int test = 1; int cnt; Circle circle; Class cl; Class[] temp; System.out.println("Circle architecture tests..."); circle = new Circle(5.6789, new Point(-99, 66), Color.cyan, false); cl = circle.getClass(); pass &= test(cl.getConstructors().length == 1, test++); pass &= test((temp = cl.getInterfaces()).length == 1, test++); pass &= test(temp[0].getName().equals("Shape"), test++); pass &= test(verifyEqualsMethodSignature(cl), test++); cnt = countModifiers(cl.getDeclaredMethods(), Modifier.PUBLIC); pass &= test(cnt == 10, test++); cnt = cl.getFields().length; pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED); pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE); pass &= test(cnt == 4, test++); // Count and test number of of PACKAGE fields cnt = cl.getDeclaredFields().length - countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE) - countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED) - countModifiers(cl.getDeclaredFields(), Modifier.PUBLIC); pass &= test(cnt == 0, test++); return pass; }
public void addListenerForType(String type, CalicoEventListener listener, int listenerType) { Class<?> rootClass = NetworkCommand.class; Field[] fields = rootClass.getFields(); try { for (int i = 0; i < fields.length; i++) { if (fields[i].getType() == int.class) { if (fields[i].getName().length() >= type.length() && fields[i].getName().substring(0, type.length()).compareTo(type) == 0) { fields[i].setAccessible(true); int command = fields[i].getInt(NetworkCommand.class); if (listenerType == CalicoEventHandler.ACTION_PERFORMER_LISTENER) eventListeners.get(command).add(0, listener); else eventListeners.get(command).add(listener); // eventListeners.get(command).add(listener); } } } } catch (Exception e) { e.printStackTrace(); } }
/** Instance null means get static fields. */ private Node internalGetField(String fieldName, Node instance) { boolean isStatic = instance == null; for (Field field : clazz.getFields()) { if (field.getName().equals(fieldName) && Modifier.isStatic(field.getModifiers()) == isStatic) { return new ReflectionBaseField(field); } } List<Method> matchingMethods = new ArrayList<>(); for (Method method : clazz.getMethods()) { if (method.getName().equals(fieldName) && Modifier.isStatic(method.getModifiers()) == isStatic) { matchingMethods.add(method); } } if (matchingMethods.isEmpty()) { // TODO improve the error returned throw new UnsolvedSymbolException(fieldName); } else { return new ReflectionBasedSetOfOverloadedMethods(matchingMethods, instance); } }
private static boolean testCanvasArch() { boolean pass = true; int test = 1; int cnt; Canvas canvas; Class cl; Class[] temp; System.out.println("Canvas architecture tests..."); canvas = new Canvas(); cl = canvas.getClass(); pass &= test(cl.getConstructors().length == 1, test++); cnt = countModifiers(cl.getDeclaredMethods(), Modifier.PUBLIC); pass &= test(cnt == 10, test++); cnt = cl.getFields().length; pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED); pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE); pass &= test(cnt == 1, test++); // Count and test number of of PACKAGE fields cnt = cl.getDeclaredFields().length - countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE) - countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED) - countModifiers(cl.getDeclaredFields(), Modifier.PUBLIC); pass &= test(cnt == 0, test++); return pass; }
public static void main(String[] args) { // Obtain the class object if we know the name of the class Class rental = RentCar.class; try { // get the absolute name of the class String rentalClassPackage = rental.getName(); System.out.println("Class Name is: " + rentalClassPackage); // get the simple name of the class (without package info) String rentalClassNoPackage = rental.getSimpleName(); System.out.println("Class Name without package is: " + rentalClassNoPackage); // get the package name of the class Package rentalPackage = rental.getPackage(); System.out.println("Package Name is: " + rentalPackage); // get all the constructors of the class Constructor[] constructors = rental.getConstructors(); System.out.println("Constructors are: " + Arrays.toString(constructors)); // get constructor with specific argument Constructor constructor = rental.getConstructor(Integer.TYPE); // initializing an object of the RentCar class RentCar rent = (RentCar) constructor.newInstance(455); // get all methods of the class including declared methods of // superclasses // in that case, superclass of RentCar is the class java.lang.Object Method[] allmethods = rental.getMethods(); System.out.println("Methods are: " + Arrays.toString(allmethods)); for (Method method : allmethods) { System.out.println("method = " + method.getName()); } // get all methods declared in the class // but excludes inherited methods. Method[] declaredMethods = rental.getDeclaredMethods(); System.out.println("Declared Methods are: " + Arrays.toString(declaredMethods)); for (Method dmethod : declaredMethods) { System.out.println("method = " + dmethod.getName()); } // get method with specific name and parameters Method oneMethod = rental.getMethod("computeRentalCost", new Class[] {Integer.TYPE}); System.out.println("Method is: " + oneMethod); // call computeRentalCost method with parameter int oneMethod.invoke(rent, 4); // get all the parameters of computeRentalCost Class[] parameterTypes = oneMethod.getParameterTypes(); System.out.println( "Parameter types of computeRentalCost() are: " + Arrays.toString(parameterTypes)); // get the return type of computeRentalCost Class returnType = oneMethod.getReturnType(); System.out.println("Return type is: " + returnType); // gets all the public member fields of the class RentCar Field[] fields = rental.getFields(); System.out.println("Public Fields are: "); for (Field oneField : fields) { // get public field name Field field = rental.getField(oneField.getName()); String fieldname = field.getName(); System.out.println("Fieldname is: " + fieldname); // get public field type Object fieldType = field.getType(); System.out.println("Type of field " + fieldname + " is: " + fieldType); // get public field value Object value = field.get(rent); System.out.println("Value of field " + fieldname + " is: " + value); } // How to access private member fields of the class // getDeclaredField() returns the private field Field privateField = RentCar.class.getDeclaredField("type"); String name = privateField.getName(); System.out.println("One private Fieldname is: " + name); // makes this private field instance accessible // for reflection use only, not normal code privateField.setAccessible(true); // get the value of this private field String fieldValue = (String) privateField.get(rent); System.out.println("fieldValue = " + fieldValue); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
public String getPublicPropertiesForClasses(String classNames[]) { StringBuilder result = new StringBuilder(); String className = null; ArrayList publicFields = new ArrayList(); result.append("<classDefinitions>"); if (classNames != null && classNames.length > 0) { for (int i = 0; i < classNames.length; i++) { className = classNames[i]; if (className != null) { result.append("<classDefinition>"); try { Class c = Class.forName(className); Field fields[] = c.getFields(); Field field = null; if (fields != null) { for (int k = 0; k < fields.length; k++) { field = fields[k]; if (field != null) publicFields.add( (new StringBuilder(String.valueOf(field.getName()))) .append(",") .append(field.getType().getName()) .toString()); } } try { BeanInfo b = Introspector.getBeanInfo(c); result.append( (new StringBuilder("<classSimpleName>")) .append(c.getSimpleName()) .append("</classSimpleName>") .toString()); result.append( (new StringBuilder("<classFullName>")) .append(c.getName()) .append("</classFullName>") .toString()); Package pack = c.getPackage(); String packStr = ""; if (pack != null) packStr = pack.getName(); result.append( (new StringBuilder("<packageName>")) .append(packStr) .append("</packageName>") .toString()); PropertyDescriptor pds[] = b.getPropertyDescriptors(); if (pds != null) { for (int propCount = 0; propCount < pds.length; propCount++) { PropertyDescriptor pd = pds[propCount]; String propertyName = pd.getName(); Method readMethod = pd.getReadMethod(); Method writeMethod = pd.getWriteMethod(); if (readMethod != null && isPublicAccessor(readMethod.getModifiers()) && writeMethod != null && isPublicAccessor(writeMethod.getModifiers())) publicFields.add( (new StringBuilder(String.valueOf(propertyName))) .append(",") .append(pd.getPropertyType().getName()) .toString()); } } } catch (Exception e) { e.printStackTrace(); } if (publicFields != null && publicFields.size() > 0) { String temp = null; result.append("<publicFields>"); for (int counter = 0; counter < publicFields.size(); counter++) { temp = (String) publicFields.get(counter); if (temp != null) { String pubTemp[] = temp.split(","); if (pubTemp.length == 2) { result.append("<publicField>"); result.append( (new StringBuilder("<publicFieldName>")) .append(pubTemp[0]) .append("</publicFieldName>") .toString()); result.append( (new StringBuilder("<publicFieldType>")) .append(pubTemp[1]) .append("</publicFieldType>") .toString()); result.append("</publicField>"); } } } result.append("</publicFields>"); } } catch (ClassNotFoundException e) { result.append( (new StringBuilder("<classFullName>")) .append(className) .append("</classFullName>") .toString()); result.append( (new StringBuilder("<error>Problem retrieving ")) .append(className) .append(" information</error>") .toString()); System.out.println(e.getMessage()); } result.append("</classDefinition>"); } } } result.append("</classDefinitions>"); return result.toString(); }
public String getDestinations(String messageBrokerId) { StringBuilder result = new StringBuilder(); MessageBroker broker = MessageBroker.getMessageBroker(messageBrokerId); result.append("<remotingDestinations>"); if (broker != null) { Service remotingService = broker.getServiceByType("flex.messaging.services.RemotingService"); if (remotingService != null) { Map destinations = remotingService.getDestinations(); Iterator destinationsIterator = destinations.keySet().iterator(); result.append("<destinations>"); if (destinationsIterator != null) { while (destinationsIterator.hasNext()) { RemotingDestination destination = (RemotingDestination) destinations.get(destinationsIterator.next()); if (destination != null) { result.append("<destination>"); result.append( (new StringBuilder("<destinationId>")) .append(destination.getId()) .append("</destinationId>") .toString()); result.append( (new StringBuilder("<adapterName>")) .append(destination.getAdapter().getClass().getName()) .append("</adapterName>") .toString()); result.append( (new StringBuilder("<source>")) .append(destination.getSource()) .append("</source>") .toString()); List channelIds = destination.getChannels(); Iterator channelIdsIterator = channelIds.iterator(); result.append("<channels>"); for (; channelIdsIterator.hasNext(); result.append( (new StringBuilder("<channel>")) .append((String) channelIdsIterator.next()) .append("</channel>") .toString())) ; result.append("</channels>"); SecurityConstraint secConstraint = destination.getSecurityConstraint(); result.append("<securityConstraint>"); if (secConstraint != null) { result.append( (new StringBuilder("<securityMethod>")) .append(secConstraint.getMethod()) .append("</securityMethod>") .toString()); result.append( (new StringBuilder("<securityRoles>")) .append(secConstraint.getRoles()) .append("</securityRoles>") .toString()); } result.append("</securityConstraint>"); String className = destination.getSource(); if (className != null) try { Class c = Class.forName("com.adams.dt.util.Abstract"); Field fields[] = c.getFields(); result.append("<fields>"); if (fields != null) { for (int i = 0; i < fields.length; i++) result.append( (new StringBuilder("<field>")) .append(fields[i].toString()) .append("</field>") .toString()); } result.append("</fields>"); Method methods[] = c.getMethods(); result.append("<methods>"); if (methods != null) { for (int i = 0; i < methods.length; i++) if (methods[i] != null && !methodsExclude.contains(methods[i].getName())) { result.append("<method>"); result.append( (new StringBuilder("<methodSignature>")) .append(methods[i].toString()) .append("</methodSignature>") .toString()); result.append( (new StringBuilder("<methodName>")) .append(methods[i].getName()) .append("</methodName>") .toString()); result.append( (new StringBuilder("<returnType>")) .append(methods[i].getReturnType().getName()) .append("</returnType>") .toString()); Class paramClasses[] = methods[i].getParameterTypes(); result.append("<params>"); if (paramClasses != null) { for (int j = 0; j < paramClasses.length; j++) if (paramClasses[j] != null) result.append( (new StringBuilder("<param>")) .append(paramClasses[j].getName()) .append("</param>") .toString()); } result.append("</params>"); result.append("</method>"); } } result.append("</methods>"); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } result.append("</destination>"); } } result.append("</destinations>"); } } } result.append("</remotingDestinations>"); return result.toString(); }