List of usage examples for java.lang Class getMethods
@CallerSensitive public Method[] getMethods() throws SecurityException
From source file:com.flexoodb.engines.FlexJAXBDBDataEngine2.java
private void reviveObject(String parentid, Object o, Connection conn, String prefix, boolean revivechildren) throws Exception { Vector v = new Vector(); try {/*from www .j a v a 2 s .co m*/ Class c = o.getClass(); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().startsWith("get") && method.getReturnType() != null && !method.getReturnType().getSimpleName().equals("Class")) { Class ret = method.getReturnType(); if (ret.getSimpleName().equals("List")) { Object[] args = null; List list = (ArrayList) method.invoke(o, args); ParameterizedType t = (ParameterizedType) method.getGenericReturnType(); Type type = t.getActualTypeArguments()[0]; String[] s = ("" + type).split(" "); String classname = s[1].substring(s[1].lastIndexOf(".") + 1); String tablename = prefix + classname.toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn.prepareStatement( "select id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found while (rec != null && rec.next()) { String id = rec.getString("id"); //Object o2 = _flexutils.getObject(rec.getString("content"),Class.forName(s[1])); Object o2 = _flexutils.getObject(rec.getString("content"), ClassLoader.getSystemClassLoader().loadClass(s[1])); if (id != null && o2 != null && !id.equalsIgnoreCase(parentid)) { list.add(o2); } } } } else if (!ret.getName().startsWith("java") && !ret.getSimpleName().toLowerCase().endsWith("byte[]") && !ret.getSimpleName().toLowerCase().equals("int")) // if complex { String tablename = prefix + ret.getSimpleName().toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn .prepareStatement("select distinct id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found if (rec != null && rec.next()) { String id = rec.getString("id"); Object o2 = _flexutils.getObject(rec.getString("content"), ret); if (o2 != null && !id.equalsIgnoreCase(parentid)) { String setmethod = "set" + method.getName().substring(3); Object[] args = new Object[1]; args[0] = o2; Class[] cls = new Class[1]; cls[0] = o2.getClass(); Method met = c.getMethod(setmethod, cls); met.invoke(o, args); if (revivechildren) { reviveObject(id, o2, conn, prefix, revivechildren); } //System.out.println(">>> "+o2+" added!"); } /*if (rec.isLast()) { break; }*/ } } } } } } catch (Exception f) { throw f; } }
From source file:com.flexoodb.engines.FlexJAXBDBDataEngine.java
private void reviveObject(String parentid, Object o, Connection conn, String prefix, boolean revivechildren) throws Exception { Vector v = new Vector(); try {// www .j a va 2 s . c om Class c = o.getClass(); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().startsWith("get") && method.getReturnType() != null && !method.getReturnType().getSimpleName().equals("Class")) { Class ret = method.getReturnType(); if (ret.getSimpleName().equals("List")) { Object[] args = null; List list = (ArrayList) method.invoke(o, args); ParameterizedType t = (ParameterizedType) method.getGenericReturnType(); Type type = t.getActualTypeArguments()[0]; String[] s = ("" + type).split(" "); String classname = s[1].substring(s[1].lastIndexOf(".") + 1); String tablename = prefix + classname.toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn.prepareStatement( "select id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found while (rec != null && rec.next()) { String id = rec.getString("id"); //Object o2 = _flexutils.getObject(rec.getString("content"),Class.forName(s[1])); Object o2 = _flexutils.getObject(rec.getString("content"), ClassLoader.getSystemClassLoader().loadClass(s[1])); if (id != null && o2 != null && !id.equalsIgnoreCase(parentid)) { list.add(o2); } } } } else if (!ret.getName().startsWith("java") && !ret.getSimpleName().toLowerCase().endsWith("byte[]") && !ret.getSimpleName().toLowerCase().equals("int")) // if complex { String tablename = prefix + ret.getSimpleName().toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn .prepareStatement("select distinct id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found if (rec != null && rec.next()) { String id = rec.getString("id"); Object o2 = _flexutils.getObject(rec.getString("content"), ret); if (o2 != null && !id.equalsIgnoreCase(parentid)) { String setmethod = "set" + method.getName().substring(3); Object[] args = new Object[1]; args[0] = o2; Class[] cls = new Class[1]; cls[0] = o2.getClass(); Method met = c.getMethod(setmethod, cls); met.invoke(o, args); if (revivechildren) { reviveObject(id, o2, conn, prefix, revivechildren); } //System.out.println(">>> "+o2+" added!"); } /*if (rec.isLast()) { break; }*/ } } } } } } catch (Exception f) { throw f; } }
From source file:cn.webwheel.ActionSetter.java
public List<SetterInfo> parseSetters(Class cls) { List<SetterInfo> list = new ArrayList<SetterInfo>(); Field[] fields = cls.getFields(); for (int i = fields.length - 1; i >= 0; i--) { Field field = fields[i];/*from w w w .j av a 2 s . co m*/ if (Modifier.isFinal(field.getModifiers())) continue; if (Modifier.isStatic(field.getModifiers())) continue; WebParam param = field.getAnnotation(WebParam.class); String name = field.getName(); if (field.getType().isArray()) name += "[]"; if (param != null && !param.value().isEmpty()) name = param.value(); SetterInfo si = getSetterInfo(field, name); if (si == null) { if (param != null) { logger.severe("wrong WebParam used at " + field); } continue; } list.add(si); } Method[] methods = cls.getMethods(); for (int i = methods.length - 1; i >= 0; i--) { Method method = methods[i]; WebParam param = method.getAnnotation(WebParam.class); String name = isSetter(method); if (name == null) { continue; } if (method.getParameterTypes()[0].isArray()) { name += "[]"; } if (param != null && !param.value().isEmpty()) { name = param.value(); } SetterInfo si = getSetterInfo(method, name); if (si == null) { if (param != null) { logger.severe("wrong WebParam used at " + method); } continue; } list.add(si); } return list; }
From source file:com.espertech.esper.dataflow.core.DataFlowServiceImpl.java
private LogicalChannelBindingMethodDesc findMatchingMethod(String operatorName, Class target, LogicalChannel channelDesc, boolean isPunctuation) throws ExprValidationException { if (isPunctuation) { for (Method method : target.getMethods()) { if (method.getName().equals("onSignal")) { return new LogicalChannelBindingMethodDesc(method, LogicalChannelBindingTypePassAlong.INSTANCE); }//from w w w . j a v a 2s . co m } return null; } LogicalChannelProducingPortCompiled outputPort = channelDesc.getOutputPort(); Class[] expectedIndividual; Class expectedUnderlying; EventType expectedUnderlyingType; GraphTypeDesc typeDesc = outputPort.getGraphTypeDesc(); if (typeDesc.isWildcard()) { expectedIndividual = new Class[0]; expectedUnderlying = null; expectedUnderlyingType = null; } else { expectedIndividual = new Class[typeDesc.getEventType().getPropertyNames().length]; int i = 0; for (EventPropertyDescriptor descriptor : typeDesc.getEventType().getPropertyDescriptors()) { expectedIndividual[i] = descriptor.getPropertyType(); i++; } expectedUnderlying = typeDesc.getEventType().getUnderlyingType(); expectedUnderlyingType = typeDesc.getEventType(); } String channelSpecificMethodName = null; if (channelDesc.getConsumingOptStreamAliasName() != null) { channelSpecificMethodName = "on" + channelDesc.getConsumingOptStreamAliasName(); } for (Method method : target.getMethods()) { boolean eligible = method.getName().equals("onInput"); if (!eligible && method.getName().equals(channelSpecificMethodName)) { eligible = true; } if (!eligible) { continue; } // handle Object[] int numParams = method.getParameterTypes().length; Class[] paramTypes = method.getParameterTypes(); if (expectedUnderlying != null) { if (numParams == 1 && JavaClassHelper.isSubclassOrImplementsInterface(paramTypes[0], expectedUnderlying)) { return new LogicalChannelBindingMethodDesc(method, LogicalChannelBindingTypePassAlong.INSTANCE); } if (numParams == 2 && JavaClassHelper.getBoxedType(paramTypes[0]) == Integer.class && JavaClassHelper.isSubclassOrImplementsInterface(paramTypes[1], expectedUnderlying)) { return new LogicalChannelBindingMethodDesc(method, new LogicalChannelBindingTypePassAlongWStream(channelDesc.getConsumingOpStreamNum())); } } if (numParams == 1 && (paramTypes[0] == Object.class || (paramTypes[0] == Object[].class && method.isVarArgs()))) { return new LogicalChannelBindingMethodDesc(method, LogicalChannelBindingTypePassAlong.INSTANCE); } if (numParams == 2 && paramTypes[0] == int.class && (paramTypes[1] == Object.class || (paramTypes[1] == Object[].class && method.isVarArgs()))) { return new LogicalChannelBindingMethodDesc(method, new LogicalChannelBindingTypePassAlongWStream(channelDesc.getConsumingOpStreamNum())); } // if exposing a method that exactly matches each property type in order, use that, i.e. "onInut(String p0, int p1)" if (expectedUnderlyingType instanceof ObjectArrayEventType && JavaClassHelper.isSignatureCompatible(expectedIndividual, method.getParameterTypes())) { return new LogicalChannelBindingMethodDesc(method, LogicalChannelBindingTypeUnwind.INSTANCE); } } Set<String> choices = new LinkedHashSet<String>(); choices.add(Object.class.getSimpleName()); choices.add("Object[]"); if (expectedUnderlying != null) { choices.add(expectedUnderlying.getSimpleName()); } throw new ExprValidationException("Failed to find onInput method on for operator '" + operatorName + "' class " + target.getName() + ", expected an onInput method that takes any of {" + CollectionUtil.toString(choices) + "}"); }
From source file:com.clican.pluto.dataprocess.dpl.impl.DplStatementImpl.java
/** * @see DplStatement#execute(String, ProcessorContext, Class) *//*from w w w . j a v a 2 s . co m*/ @SuppressWarnings("unchecked") public <T> List<T> execute(String dpl, ProcessorContext context, Class<T> clazz) throws DplException { List<Map<String, Object>> list = this.execute(dpl, context); if (clazz == null) { return (List<T>) list; } List<T> result = new ArrayList<T>(); for (Map<String, Object> row : list) { T t = null; // ?? if (row.size() == 1) { t = (T) row.entrySet().iterator().next().getValue(); } else { // ???clazz???? try { t = clazz.newInstance(); } catch (Exception e) { throw new DplException(e); } Method[] methods = clazz.getMethods(); Map<String, Method> methodMap = new HashMap<String, Method>(); for (Method method : methods) { methodMap.put(method.getName(), method); methodMap.put(method.getName().toLowerCase(), method); } for (String name : row.keySet()) { try { if (row.get(name) != null) { String setMethodName = com.clican.pluto.common.util.StringUtils.getSetMethodName(name); Object value = row.get(name); if (methodMap.containsKey(setMethodName) || methodMap.containsKey(setMethodName.toLowerCase())) { Class type = methodMap.get(setMethodName.toLowerCase()).getParameterTypes()[0]; if (!value.getClass().equals(type)) { if (value instanceof Number) { value = TypeUtils.numberToNumber((Number) value, type); } else if (value instanceof String) { value = TypeUtils.stringToNumber((String) value, type); } } if (methodMap.containsKey(setMethodName)) { methodMap.get(setMethodName).invoke(t, new Object[] { value }); } else { methodMap.get(setMethodName.toLowerCase()).invoke(t, new Object[] { value }); } } else { if (log.isTraceEnabled()) { log.trace("There is no this property [" + name + "]"); } } } } catch (Exception e) { if (log.isTraceEnabled()) { log.trace("There is no this property [" + name + "]"); } } } } result.add(t); } return result; }
From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java
private HashMap<Method, String> getFieldMapping(Class cls, int type, Boolean isCamelCased, Boolean useDeclaredOnly) { HashMap<Method, String> fieldMapping = new HashMap<>(); Method[] methods;//w w w . j a v a 2 s . co m if (useDeclaredOnly) { methods = cls.getDeclaredMethods(); } else { methods = cls.getMethods(); } for (Method method : methods) { if (method.getAnnotation(Transient.class) == null) { String methodName = method.getName(); if (type == GET) { if (methodName.startsWith("get") && !methodName.equals("getClass")) { fieldMapping.put(method, getDbName(isCamelCased, methodName.substring(3), method)); } } else { if (methodName.startsWith("set") && !methodName.equals("getClass")) { fieldMapping.put(method, getDbName(isCamelCased, methodName.substring(3), method)); } } } } return fieldMapping; }
From source file:com.flexoodb.engines.FlexJAXBDBDataEngine.java
private Hashtable<Method, Class> retrieveMethods(Class c) { Hashtable<Method, Class> methods = new Hashtable<Method, Class>(); try {//from ww w . ja v a2s . co m // if this generates a fault then it must be abstract and we ignore it. c.newInstance(); Method[] m = c.getMethods(); int x = 0; for (int i = 0; i < m.length; i++) { if (m[i].getReturnType() != null && !m[i].getReturnType().getSimpleName().equals("Class")) { methods.put(m[i], c); } } } catch (Exception e) { //e.printStackTrace(); } return methods; }
From source file:alice.tuprolog.lib.OOLibrary.java
private static Method lookupMethod(Class<?> target, String name, Class<?>[] argClasses, Object[] argValues) throws NoSuchMethodException { // first try for exact match try {/*from ww w . j a v a2s .com*/ Method m = target.getMethod(name, argClasses); return m; } catch (NoSuchMethodException e) { if (argClasses.length == 0) { // if no args & no exact match, out of // luck return null; } } // go the more complicated route Method[] methods = target.getMethods(); Vector<Method> goodMethods = new Vector<>(); for (int i = 0; i != methods.length; i++) { if (name.equals(methods[i].getName()) && matchClasses(methods[i].getParameterTypes(), argClasses)) goodMethods.addElement(methods[i]); } switch (goodMethods.size()) { case 0: // no methods have been found checking for assignability // and (int -> long) conversion. One last chance: // looking for compatible methods considering also // type conversions: // double --> float // (the first found is used - no most specific // method algorithm is applied ) for (int i = 0; i != methods.length; i++) { if (name.equals(methods[i].getName())) { Class<?>[] types = methods[i].getParameterTypes(); Object[] val = matchClasses(types, argClasses, argValues); if (val != null) { // found a method compatible // after type conversions for (int j = 0; j < types.length; j++) { argClasses[j] = types[j]; argValues[j] = val[j]; } return methods[i]; } } } return null; case 1: return goodMethods.firstElement(); default: return mostSpecificMethod(goodMethods); } }
From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java
/** * @param leftSide/*from ww w . ja v a2s .c o m*/ * @param rightSide * @param leftSideVarName * @param isMappedBy * @return */ @SuppressWarnings("cast") protected String getRightSideForManyToMany(final Class<?> leftSide, final Class<?> rightSide, final String leftSideVarName) { for (Method method : rightSide.getMethods()) { String methodName = method.getName(); // Skip if it is a not a getter if (!methodName.startsWith("get")) { continue; } //System.out.println("getRightSideForManyToMany Left Class["+leftSide.getSimpleName()+"] Right["+rightSide.getSimpleName()+"] Right Side Method ["+methodName+"] Ret["+method.getReturnType().getSimpleName()+"]"); // Skip if it is a not a ManyToOne if (!method.isAnnotationPresent(javax.persistence.ManyToMany.class)) { continue; } Class<?> retType = method.getReturnType(); boolean isSet = Collection.class.isAssignableFrom(retType); if (isSet) { Class<?> rt = getSetsClassType(rightSide, methodName); if (rt == null) { continue; // probably because of an interface } retType = rt; //System.out.println("Set["+(retType != null ? retType.getSimpleName() : "NULL")+"]"); } if (leftSide == retType) { javax.persistence.ManyToMany manyToMany = (javax.persistence.ManyToMany) method .getAnnotation(javax.persistence.ManyToMany.class); // Caller wasn't mappedBy so look for mapped By String othersideName = manyToMany.mappedBy(); if (StringUtils.isNotEmpty(othersideName) && leftSideVarName.equals(othersideName)) { return getFieldNameFromMethod(method); } } } return null; }
From source file:com.flexoodb.engines.FlexJAXBMappedDBDataEngine.java
private void reviveObject(String parentid, FlexContainer parent, Connection conn, String prefix, boolean revivechildren) throws Exception { Vector v = new Vector(); try {//from w w w .ja v a 2 s .c o m Class c = parent.getObject().getClass(); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().startsWith("get") && method.getReturnType() != null && !method.getReturnType().getSimpleName().equals("Class")) { Class ret = method.getReturnType(); if (ret.getSimpleName().equals("List")) { Object[] args = null; //List list = (ArrayList) method.invoke(parent.getObject(), args); List list = new Vector<FlexContainer>(); ParameterizedType t = (ParameterizedType) method.getGenericReturnType(); Type type = t.getActualTypeArguments()[0]; String[] s = ("" + type).split(" "); String classname = s[1].substring(s[1].lastIndexOf(".") + 1); String tablename = classname.toLowerCase(); tablename = tablename.endsWith("type") ? tablename.substring(0, tablename.lastIndexOf("type")) : tablename; //FlexElement element = _elements.get(prefix+tablename); FlexElement element = _elements.get(tablename); String idcolumn = element.getAttribute("idcolumn").getValue(); String realtablename = element.getAttribute("realtablename").getValue(); String parentidcolumn = element.getAttribute("parentidcolumn").getValue(); boolean includeidcolumns = element.getAttribute("includeidcolumns").getValue() == null ? false : (element.getAttribute("includeidcolumns").getValue().equalsIgnoreCase("true")); //System.out.println("t:"+tablename+" "+realtablename+" >"+"select * from "+prefix+((realtablename!=null)?realtablename:tablename.toLowerCase())+" where "+parentidcolumn+"=?"+"<"); FlexElement idelement = element.getElementByName(parentidcolumn); PreparedStatement ps = (PreparedStatement) conn.prepareStatement("select * from " + prefix + ((realtablename != null) ? realtablename : tablename.toLowerCase()) + " where " + parentidcolumn + "=?"); //PreparedStatement ps = (PreparedStatement) conn.prepareStatement("select * from "+((realtablename!=null)?realtablename:tablename.toLowerCase())+" where "+parentidcolumn+"=?"); if (idelement.getType().equals("string")) { ps.setString(1, parentid); } else { ps.setInt(1, Integer.parseInt(parentid)); } //System.out.println(">> query:"+ps.toString()); ResultSet rec = ps.executeQuery(); RecordSet res = new RecordSet(rec); // check if a record was found while (res != null && res.next()) { //String id = res.getString("id"); String id = res.getString(idcolumn); //Object o2 = _flexutils.getObject(FlexUtils.getRDBMSRecordAsXML(tablename, res, idcolumn, parentidcolumn,includeidcolumns),Class.forName(s[1])); Object o2 = _flexutils .getObject( FlexUtils.getRDBMSRecordAsXML(tablename, res, idcolumn, parentidcolumn, includeidcolumns), ClassLoader.getSystemClassLoader().loadClass(s[1])); if (id != null && o2 != null) { //instead of adding this in the object's list we add it in the parent flex's //list.add(o2); FlexContainer fo = new FlexContainer(o2); fo.setId(id); fo.setParentId(parentid); list.add(fo); // then we check if this guy has children! enabling this will cause a loop of death //reviveObject(id,o2,conn); } } // finally we add it to the parent flex parent.addChildren(tablename, list); //System.out.println(">>>"+parent.getChildren()); } else if (!ret.getName().startsWith("java") && !ret.getSimpleName().toLowerCase().endsWith("byte[]") && !ret.getSimpleName().toLowerCase().equals("int")) // if complex { String tablename = ret.getSimpleName().toLowerCase(); tablename = tablename.endsWith("type") ? tablename.substring(0, tablename.lastIndexOf("type")) : tablename; FlexElement element = _elements.get(tablename); String idcolumn = element.getAttribute("idcolumn").getValue(); String realtablename = element.getAttribute("realtablename").getValue(); String parentidcolumn = element.getAttribute("parentidcolumn").getValue(); boolean includeidcolumns = element.getAttribute("includeidcolumns").getValue() == null ? false : (element.getAttribute("includeidcolumns").getValue().equalsIgnoreCase("true")); FlexElement idelement = element.getElementByName(parentidcolumn); PreparedStatement ps = (PreparedStatement) conn.prepareStatement("select * from " + prefix + ((realtablename != null) ? realtablename : tablename.toLowerCase()) + " where " + parentidcolumn + "=" + (idelement.getType().equals("string") ? ("'" + parentid + "'") : parentid)); ResultSet rec = ps.executeQuery(); // check if a record was found RecordSet res = new RecordSet(rec); if (res != null && res.size() > 0) { //String id = rec.getString("id"); String id = res.getString(idcolumn); Object o2 = _flexutils.getObject(FlexUtils.getRDBMSRecordAsXML(tablename, res, idcolumn, parentidcolumn, includeidcolumns), ret); if (o2 != null) { String setmethod = "set" + method.getName().substring(3); Object[] args = new Object[1]; args[0] = o2; Class[] cls = new Class[1]; cls[0] = o2.getClass(); Method met = c.getMethod(setmethod, cls); met.invoke(parent.getObject(), args); /*if (revivechildren) { reviveObject(id,o2,conn,prefix,revivechildren); }*/ } if (rec.last()) { break; } } } } } } catch (Exception f) { throw f; } }