private static object RunMethod(System.Type t, string methodName, object objInstance, BindingFlags eFlags, System.Type[] parameterDefinitions, object[] parameterValues) { foreach (MethodInfo m in t.GetMethods(eFlags)) { if (m.Name == methodName && MethodMatchesParameterDefinitions(m, parameterDefinitions)) { if (parameterDefinitions.Length == parameterValues.Length + 1) { throw new NotImplementedException("The case in which no args are passed to params parameter."); } // if only parameter is params arg, compiler collapses it. this re-expands it: else if (parameterDefinitions[parameterDefinitions.Length - 1] != parameterValues[parameterValues.Length - 1].GetType()) { Array unknownTypeArray = Array.CreateInstance(parameterValues[0].GetType(), parameterValues.Length); parameterValues.CopyTo(unknownTypeArray, 0); return m.Invoke(objInstance, new object[] { unknownTypeArray }); } else { return m.Invoke(objInstance, parameterValues); } } } throw new ArgumentException("There is no method '" + methodName + "' for type '" + t.ToString() + "' which matched the parameter type list."); }
private static void ProcessStaticMethodAttributes(System.Type type) { List<string> methodNames = (List<string>) null; List<RuntimeInitializeLoadType> loadTypes = (List<RuntimeInitializeLoadType>) null; MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); for (int index = 0; index < methods.GetLength(0); ++index) { MethodInfo methodInfo = methods[index]; if (Attribute.IsDefined((MemberInfo) methodInfo, typeof (RuntimeInitializeOnLoadMethodAttribute))) { RuntimeInitializeLoadType initializeLoadType = RuntimeInitializeLoadType.AfterSceneLoad; object[] customAttributes = methodInfo.GetCustomAttributes(typeof (RuntimeInitializeOnLoadMethodAttribute), false); if (customAttributes != null && customAttributes.Length > 0) initializeLoadType = ((RuntimeInitializeOnLoadMethodAttribute) customAttributes[0]).loadType; if (methodNames == null) { methodNames = new List<string>(); loadTypes = new List<RuntimeInitializeLoadType>(); } methodNames.Add(methodInfo.Name); loadTypes.Add(initializeLoadType); } if (Attribute.IsDefined((MemberInfo) methodInfo, typeof (InitializeOnLoadMethodAttribute))) methodInfo.Invoke((object) null, (object[]) null); } if (methodNames == null) return; EditorAssemblies.StoreRuntimeInitializeClassInfo(type, methodNames, loadTypes); }
/// <summary> /// Finds all Extension methods defined by a type /// </summary> /// <param name="extending_type"></param> /// <returns></returns> public static IEnumerable<ExtensionMethodRecord> EnumExtensionMethods(System.Type extending_type) { var ext_methods = extending_type.GetMethods().Where(IsExtensionMethod).ToList(); foreach (var ext_method in ext_methods) { var first_param = ext_method.GetParameters()[0]; var extended_type = first_param.ParameterType; var rec = new ExtensionMethodRecord(extending_type, extended_type, ext_method); yield return rec; } }
private static MethodInfo[] GetMethods(System.Type type) { MethodInfo[] methods = type.GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); List<MethodInfo> list = new List<MethodInfo>(); foreach (MethodInfo info in methods) { if (((info.GetBaseDefinition().DeclaringType != typeof(object)) & !info.IsSpecialName) && !info.IsAbstract) { list.Add(info); } } return list.ToArray(); }
/// <summary> /// Overrides all methods in the given interface type with methods that throw a <see cref="NotImplementedException"/>. /// </summary> /// <param name="interfaceType">The interface type that will be implemented by the target type.</param> /// <param name="type">The target type.</param> /// <returns>The list of stubbed methods.</returns> private static IEnumerable<MethodDefinition> CreateInterfaceStub(System.Type interfaceType, TypeDefinition type) { var module = type.Module; var overrider = new MethodOverrider(); var methods = interfaceType.GetMethods(); var stubbedMethods = new List<MethodDefinition>(); foreach (var method in methods) { var newMethod = CreateMethodStub(type, module, overrider, method); stubbedMethods.Add(newMethod); } return stubbedMethods; }
public static IEnumerable<System.Type> GetTypeInterfaceGenericArguments(System.Type type, System.Type interfaceType) { System.Type[] arguments = interfaceType.GetGenericArguments(); if (arguments != null) { return arguments; } if (interfaceType == typeof(ICollection<>)) { return type.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance). Where(methodInfo => methodInfo.Name == "Add" && methodInfo.ParameterTypes.Length == 1).First().ParameterTypes; } if (interfaceType == typeof(IDictionary<,>)) { return type.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance). Where(methodInfo => methodInfo.Name == "Add" && methodInfo.ParameterTypes.Length == 2).First().ParameterTypes; } throw new Granular.Exception("Can't get generic arguments for type \"{0}\" interface \"{1}\"", type.Name, interfaceType.Name); }
internal void AddOperationsFromType(System.Type type) { foreach (MethodInfo info in type.GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance)) { if (info.GetCustomAttributes(typeof(WebGetAttribute), true).Length != 0) { this.AddServiceOperation(info, "GET"); } else if (info.GetCustomAttributes(typeof(WebInvokeAttribute), true).Length != 0) { this.AddServiceOperation(info, "POST"); } } }
public static object CallMethod(object target, System.Type type, string methodCMD) { string method_str = ""; string parasCMD = ""; object[] paras = null; method_str = methodCMD.Substring(0,methodCMD.IndexOf("(")); parasCMD = methodCMD.Substring(methodCMD.IndexOf("("), methodCMD.Length - methodCMD.IndexOf("(")); parasCMD = parasCMD.Substring( 1, parasCMD.Length - 2); if(!parasCMD .Equals( "" )){ if(parasCMD.Contains(",")){ string[] strParas = parasCMD.Split(','); paras = new object[strParas.Length]; for (int pos = 0; pos < strParas.Length; pos++) { // TODO loop in strParas // paras[pos] = int.Parse( strParas[pos] ); // if(strParas[pos].Contains("\"")){ // paras.SetValue(parasCMD.Replace("\"",""),pos); // } // // else // paras.SetValue(int.Parse(strParas[pos]),pos); paras.SetValue(GetParaFromString(strParas[pos]),pos); } }else{ paras = new object[1]; paras.SetValue(GetParaFromString(parasCMD),0); // if(parasCMD.Contains("\"")){ // parasCMD = parasCMD.Replace("\"",""); // paras.SetValue(parasCMD,0); //// paras.SetValue(parasCMD,0); // } // else // paras.SetValue(int.Parse(parasCMD),0); // paras[0] = int.Parse( parasCMD ); } } MethodInfo[] thods = type.GetMethods(); // MethodInfo method = type.GetMethod(method_str,System.Reflection.BindingFlags.); MethodInfo method = type.GetMethod(method_str); if( null == method){ XLogger.Log(target + " not have a " + method_str + " method." ); return null; } object returnValue = method.Invoke(target,paras); return returnValue; }
protected object GetBusinessObject(string name, System.Type type, params object[] parameters) { object businessObjects = Session[name]; if (businessObjects == null || (!object.ReferenceEquals(businessObjects.GetType(), type)) ) { foreach (MethodInfo method in type.GetMethods()) // Looking for a method which returns Business Object of type pased in parm { if (object.ReferenceEquals(method.ReturnType, type) && !method.IsConstructor && method.IsStatic) { bool methodMatch = false; // Check if parameters match. ParameterInfo[] methodParameters = method.GetParameters(); if (parameters == null) // no parameters { methodMatch = methodParameters.Length == 0; } else if (parameters.Length == methodParameters.Length) { methodMatch = true; // compare parameters. for (int i = 0; i <= parameters.Length - 1; i++) { if (parameters[i] == null) { methodMatch = methodMatch && methodParameters[i].IsOptional; } else { methodMatch = methodMatch && object.ReferenceEquals(parameters[i].GetType(), methodParameters[i].ParameterType); } } } if (methodMatch) // Execute it, if found. It will return Business Object with data. Save it in Session storage { try { businessObjects = method.Invoke(null, parameters); } catch { } Session[name] = businessObjects; // Save in Session storage break; } } } } return businessObjects; }
private static void ConnectDefaultHandlers(GType gtype, System.Type t) { foreach (MethodInfo minfo in t.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly)) { MethodInfo baseinfo = minfo.GetBaseDefinition (); if (baseinfo == minfo) continue; foreach (object attr in baseinfo.GetCustomAttributes (typeof (DefaultSignalHandlerAttribute), false)) { DefaultSignalHandlerAttribute sigattr = attr as DefaultSignalHandlerAttribute; MethodInfo connector = sigattr.Type.GetMethod (sigattr.ConnectionMethod, BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { typeof (GType) }, new ParameterModifier [0]); object[] parms = new object [1]; parms [0] = gtype; connector.Invoke (null, parms); break; } } }
private ContainerRowModel CreateTypeTree(System.Type type) { var children = new List<RowModel>(); object[] attrs; Attribute attr; BindingFlags flags = BindingFlags.Static | BindingFlags.Public; Lazy<object> instance = null; if (IsConstructable(type)) { flags |= BindingFlags.Instance; instance = new Lazy<object>(() => Activator.CreateInstance(type), LazyThreadSafetyMode.ExecutionAndPublication); } foreach (MethodInfo method in type.GetMethods(flags).Where(m => IsTestMethod(m, true, true, true))) { // Create a row for this method attrs = method.GetCustomAttributes(true); attr = FindAttribute(attrs, "TestAttribute") ?? FindAttribute(attrs, "BenchmarkAttribute"); var eea = FindAttribute(attrs, "ExpectedExceptionAttribute"); bool isTestSet = method.IsStatic && MayBeTestSuite(method.ReturnType) && IsTestMethod(method, true, true, false); var utt = new UnitTestTask(method, instance, attr, eea, isTestSet); var row = new TaskRowModel(method.Name, TestNodeType.Test, utt, true); if (IsTestMethod(method, false, false, true)) // benchmark? row.BasePriority--; // Give benchmarks low priority by default children.Add(row); } foreach (Type nested in type.GetNestedTypes().Where(IsTestFixtureOrSuite)) children.Add(CreateTypeTree(nested)); // Create a row for this type var result = new ContainerRowModel(type.Name, TestNodeType.TestFixture, children); result.SetSummary(type.FullName); attrs = type.GetCustomAttributes(true); attr = FindAttribute(attrs, "TestFixtureAttribute"); string description = GetPropertyValue<string>(attr, "Description", null); if (description != null) result.SetSummary(string.Format("{0} ({1})", description, type.FullName)); return result; }
internal static IEnumerable<System.Reflection.MethodInfo> GetCommandMethods(System.Type mytype) { var cmdsettype = typeof(VA.Scripting.CommandSet); if (!cmdsettype.IsAssignableFrom(mytype)) { string msg = string.Format("{0} must derive from {1}", mytype.Name, cmdsettype.Name); } var methods = mytype.GetMethods().Where(m => m.IsPublic && !m.IsStatic); foreach (var method in methods) { if (method.Name == "ToString" || method.Name == "GetHashCode" || method.Name == "GetType" || method.Name == "Equals") { continue; } yield return method; } }
internal static IEnumerable<Command> GetCommands(System.Type mytype) { var cmdsettype = typeof(CommandSet); if (!cmdsettype.IsAssignableFrom(mytype)) { string msg = $"{mytype.Name} must derive from {cmdsettype.Name}"; } var methods = mytype.GetMethods().Where(m => m.IsPublic && !m.IsStatic); foreach (var method in methods) { if (method.Name == "ToString" || method.Name == "GetHashCode" || method.Name == "GetType" || method.Name == "Equals") { continue; } var cmd = new Command(method); yield return cmd; } }
/// <summary> /// 得到一个类型中,所有标记为ControllerMethod的方法 /// </summary> /// <param name="type"></param> /// <returns></returns> private static ControllerInfo FindControllerMethods(System.Type type) { MethodInfo[] mis = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); List<ControllerMethodInfo> methodList = new List<ControllerMethodInfo>(); MethodInfo defaultMethod = null; foreach (MethodInfo mi in mis) { ControllerMethodAttribute cma = AttributeHelper.GetCustomAttribute<ControllerMethodAttribute>(mi); if (cma != null) { ControllerMethodInfo cmi = new ControllerMethodInfo(mi, cma.ForceIgnoreParameters); methodList.Add(cmi); if (defaultMethod == null && cma.Default) defaultMethod = mi; } } return new ControllerInfo(methodList.ToArray(), defaultMethod); }
/// <summary> /// Get public MethodInfos in a type. /// <param name="type">The type of the target object to get the methods.</param> /// <param name="staticMethods">If True returns only static members; otherwise returns instance members.</param> /// <returns>Public methods in a type.</returns> /// </summary> public static MethodInfo[] GetPublicMembers (System.Type type, bool staticMethods) { List<MethodInfo> methodInfos = new List<MethodInfo>(); BindingFlags bindingFlags = staticMethods ? BindingFlags.Public | BindingFlags.Static : BindingFlags.Public | BindingFlags.Instance; foreach (MethodInfo method in type.GetMethods(bindingFlags)) { Type returnType = method.ReturnParameter.ParameterType; if (returnType == typeof(void) || FunctionUtility.IsSupported(returnType)) { bool validParameters = true; foreach (ParameterInfo parameter in method.GetParameters()) { if (!FunctionUtility.IsSupported(parameter.ParameterType)) { validParameters = false; break; } } if (validParameters) methodInfos.Add(method); } } return methodInfos.ToArray(); }
public NodeMigrationData MigrateXmlNode(WorkspaceModel homespace, XmlNode elNode, System.Type type, Version workspaceVersion) { var migrations = (from method in type.GetMethods() let attribute = method.GetCustomAttributes(false).OfType<NodeMigrationAttribute>().FirstOrDefault() where attribute != null let result = new { method, attribute.From, attribute.To } orderby result.From select result).ToList(); var currentVersion = MigrationManager.VersionFromWorkspace(homespace); XmlElement nodeToMigrate = elNode as XmlElement; NodeMigrationData migrationData = new NodeMigrationData(elNode.OwnerDocument); migrationData.AppendNode(elNode as XmlElement); while (workspaceVersion != null && workspaceVersion < currentVersion) { var nextMigration = migrations.FirstOrDefault(x => x.From >= workspaceVersion); if (nextMigration == null) break; object ret = nextMigration.method.Invoke(this, new object[] { migrationData }); migrationData = ret as NodeMigrationData; if(DynamoModel.EnableMigrationLogging) { // record migration data for successful migrations migrationReport.AddMigrationDataToNodeMap(nodeToMigrate.Name, migrationData.MigratedNodes); } workspaceVersion = nextMigration.To; } return migrationData; }
private IEnumerable<MethodInfo> GetProxiableMethods(System.Type type, IEnumerable<System.Type> interfaces) { const BindingFlags candidateMethodsBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; return type.GetMethods(candidateMethodsBindingFlags) .Where(method=> method.IsProxiable()) .Concat(interfaces.SelectMany(interfaceType => interfaceType.GetMethods())).Distinct(); }
public static Hashtable GetMethodsByAttribute(System.Type parentType, System.Type attributeType) { try { var retval = new Hashtable(); var methods = parentType.GetMethods(); foreach (var m in methods) { var attributes = m.GetCustomAttributes(attributeType, true); if (attributes.Length > 0) { retval.Add(attributes[0], m); } } //Sort the array return retval; } catch (Exception ex) { throw; } }
private MethodInfo FindMethodForType(CallSite site, System.Type otype, string name, bool isStatic, object[] args, out object[] outArgs) { BindingFlags bindingFlags = isStatic ? BindingFlags.Static | BindingFlags.FlattenHierarchy : BindingFlags.Instance; var methods = otype.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | bindingFlags); var len = methods.Length; for (var mi = 0; mi < len; mi++) { var m = methods[mi]; if ((m.IsStatic == isStatic) && m.Name == name) { // attempt to convert method parameters if (Dynamic.ConvertMethodParameters(m, args, out outArgs)) { return m; } } } // method not found outArgs = null; return null; }
/// throws an exception if the current user does not have enough permission to access the method; /// this uses a custom attribute associated with the method of the connector static public bool CheckUserPermissionsForMethod(System.Type AConnectorType, string AMethodName, string AParameterTypes, Int32 ALedgerNumber) { MethodInfo[] methods = AConnectorType.GetMethods(); MethodInfo MethodToTest = null; AParameterTypes = AParameterTypes.Replace("[]", ".ARRAY"); foreach (MethodInfo method in methods) { if (method.Name == AMethodName) { string ParameterTypes = ";"; ParameterInfo[] Parameters = method.GetParameters(); foreach (ParameterInfo Parameter in Parameters) { string ParameterName = Parameter.ParameterType.ToString().Replace("&", ""); ParameterName = ParameterName.Replace("System.Collections.Generic.Dictionary`2", "DICTIONARY"); ParameterName = ParameterName.Replace("Ict.Common.", string.Empty); ParameterName = ParameterName.Replace("Ict.Petra.Shared.MCommon.", string.Empty); ParameterName = ParameterName.Replace("System.", string.Empty); if (ParameterName.Contains(".")) { ParameterName = ParameterName.Substring(ParameterName.LastIndexOf(".") + 1); } ParameterName = ParameterName.Replace("`1", string.Empty); ParameterName = ParameterName.Replace("`2", string.Empty); ParameterName = ParameterName.Replace("Boolean", "bool"); ParameterName = ParameterName.Replace("Int32", "int"); ParameterName = ParameterName.Replace("Int64", "long"); ParameterName = ParameterName.Replace("[]", ".Array"); ParameterTypes += ParameterName + ";"; } ParameterTypes = ParameterTypes.ToUpper(); if (ParameterTypes == AParameterTypes) { MethodToTest = method; break; } } } if (MethodToTest != null) { System.Object[] attributes = MethodToTest.GetCustomAttributes(typeof(RequireModulePermissionAttribute), false); if ((attributes != null) && (attributes.Length > 0)) { RequireModulePermissionAttribute requiredModules = (RequireModulePermissionAttribute)attributes[0]; string moduleExpression = requiredModules.RequiredModulesExpression.ToUpper(); if (moduleExpression == "NONE") { return true; } try { CheckUserModulePermissions(moduleExpression); if (ALedgerNumber != -1) { CheckUserModulePermissions(LEDGER_MODULESTRING + ALedgerNumber.ToString("0000")); } } catch (ESecurityModuleAccessDeniedException Exc) { string msg = String.Format(Catalog.GetString( "Module access permission was violated for method '{0}' in Connector class '{1}': Required Module access permission: {2}, UserName: {3}"), AMethodName, AConnectorType, Exc.Module, Exc.UserName); TLogging.Log(msg); Exc.Context = AMethodName + " [raised by ModuleAccessManager]"; throw; } catch (ArgumentException argException) { throw new EOPAppException("Problem with ModulePermissions, " + argException.Message + ": '" + moduleExpression + "' for " + AConnectorType.ToString() + "." + AMethodName + "()", argException); } return true; } } // TODO: resolve module permission from namespace? throw new EOPAppException( "Missing definition of access permission for method " + AMethodName + " in Connector class " + AConnectorType); }
/// <summary> Derive a ranking based on how "natural" the conversion is. /// The special value CONVERSION_NONE means no conversion is possible, /// and CONVERSION_NONTRIVIAL signals that more type conformance testing /// is required. /// Based on /// <a href="http://www.mozilla.org/js/liveconnect/lc3_method_overloading.html"> /// "preferred method conversions" from Live Connect 3</a> /// </summary> internal static int GetConversionWeight(System.Object fromObj, System.Type to) { int fromCode = GetJSTypeCode (fromObj); switch (fromCode) { case JSTYPE_UNDEFINED: if (to == typeof (string) || to == typeof (object)) { return 1; } break; case JSTYPE_NULL: if (!to.IsPrimitive) { return 1; } break; case JSTYPE_BOOLEAN: if (to == typeof (bool)) { return 1; } else if (to == typeof (object)) { return 2; } else if (to == typeof (string)) { return 3; } break; case JSTYPE_NUMBER: if (to.IsPrimitive) { if (to == typeof (double)) { return 1; } else if (to != typeof (bool)) { return 1 + GetSizeRank (to); } } else { if (to == typeof (string)) { // native numbers are #1-8 return 9; } else if (to == typeof (object)) { return 10; } else if (CliHelper.IsNumberType (to)) { // "double" is #1 return 2; } } break; case JSTYPE_STRING: if (to == typeof (string)) { return 1; } else if (to.IsInstanceOfType (fromObj)) { return 2; } else if (to.IsPrimitive) { if (to == typeof (char)) { return 3; } else if (to != typeof (bool)) { return 4; } } break; case JSTYPE_CLI_CLASS: if (to == typeof (Type)) { return 1; } else if (to == typeof (object)) { return 3; } else if (to == typeof (string)) { return 4; } break; case JSTYPE_CLI_OBJECT: case JSTYPE_CLI_ARRAY: object cliObj = fromObj; if (cliObj is Wrapper) { cliObj = ((Wrapper)cliObj).Unwrap (); } if (to.IsInstanceOfType (cliObj)) { return CONVERSION_NONTRIVIAL; } if (to == typeof (string)) { return 2; } else if (to.IsPrimitive && to != typeof (bool)) { return (fromCode == JSTYPE_CLI_ARRAY) ? CONVERSION_NONTRIVIAL : 2 + GetSizeRank (to); } break; case JSTYPE_OBJECT: // Other objects takes #1-#3 spots if (to == fromObj.GetType ()) { // No conversion required return 1; } if (to.IsArray) { if (fromObj is BuiltinArray) { // This is a native array conversion to a java array // Array conversions are all equal, and preferable to object // and string conversion, per LC3. return 1; } } else if (to == typeof (object)) { return 2; } else if (to == typeof (string)) { return 3; } else if (to == typeof (DateTime)) { if (fromObj is BuiltinDate) { // This is a native date to java date conversion return 1; } } else if (to.IsInterface) { if (fromObj is IFunction) { // See comments in coerceType if (to.GetMethods ().Length == 1) { return 1; } } return 11; } else if (to.IsPrimitive && to != typeof (bool)) { return 3 + GetSizeRank (to); } break; } return CONVERSION_NONE; }
/// <summary> /// Map the Java members of the specified /// class to my slots for reflection. /// </summary> private void finishSlots(System.Type type, bool staticOnly) { // map the class's fields to my slots FieldInfo[] fields = type.GetFields(); for (int i=0; i<fields.Length; i++) finishField(fields[i]); // map the class's methods to my slots MethodInfo[] methods = type.GetMethods(); for (int i=0; i<methods.Length; i++) finishMethod(methods[i], staticOnly); }
public static void DisposMethods(System.Type type,Dictionary<string,ClassMethodInfo> cmfDict){ BindingFlags options = BindingFlags | BindingFlags.Instance | BindingFlags.FlattenHierarchy; MethodInfo[] infoArray = type.GetMethods(options); foreach(MethodInfo info in infoArray){ if(info.IsGenericMethod) continue; if(info.Name.IndexOf('_') > 0 ) continue; string key = type.Namespace +"." + type.Name +"."+ info.Name; ClassMethodInfo cmf = !cmfDict.ContainsKey(key)? new ClassMethodInfo() :cmfDict[key]; cmf.fullName = key; cmf.className = type.Name; cmf.name = info.Name; cmf.returnName = info.ReturnType.Name; cmf.isStatic = info.IsStatic; cmfDict[key] = cmf; cmf.overrideList.Add(DisposMethodArgs( info.GetParameters() ) ); } }
/// <summary> Retrieves public methods for a class. In case the class is not /// public, retrieves methods with same signature as its public methods /// from public superclasses and interfaces (if they exist). Basically /// upcasts every method to the nearest acccessible method. /// </summary> private static System.Reflection.MethodInfo[] getAccessibleMethods(System.Type clazz) { System.Reflection.MethodInfo[] methods = clazz.GetMethods(); // TODO: the rest of this method is trying to determine what is supposed to be callable - I think .Net just returns what is callable return methods; /* * Short circuit for the (hopefully) majority of cases where the * clazz is public */ //UPGRADE_TODO: Method java.lang.reflect.Modifier.isPublic was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"' //UPGRADE_ISSUE: Method 'java.lang.Class.getModifiers' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangClassgetModifiers"' if (clazz.IsPublic) { return methods; } /* * No luck - the class is not public, so we're going the longer way. */ MethodInfo[] methodInfos = new MethodInfo[methods.Length]; for (int i = methods.Length; i-- > 0; ) { methodInfos[i] = new MethodInfo(methods[i]); } int upcastCount = getAccessibleMethods(clazz, methodInfos, 0); /* * Reallocate array in case some method had no accessible counterpart. */ if (upcastCount < methods.Length) { methods = new System.Reflection.MethodInfo[upcastCount]; } int j = 0; for (int i = 0; i < methodInfos.Length; ++i) { MethodInfo methodInfo = methodInfos[i]; if (methodInfo.upcast) { methods[j++] = methodInfo.method; } } return methods; }
public CellFactoryInvokerClass (System.Type aType, CellFactoryProviderAttribute aAttr) { factoryType = aType; factoryProvider = aAttr; if (ShellMethod == null) ShellMethod = this.GetType().GetMethod ("Invoke"); if (ShellMethodParameters == null) ShellMethodParameters = ShellMethod.GetParameters(); MethodInfo[] methods = aType.GetMethods(); foreach (MethodInfo method in methods) { if ((method.IsStatic == true) && (method.Name == aAttr.MethodName)) { ParameterInfo[] parms = method.GetParameters(); if (method.ReturnType != ShellMethod.ReturnType) continue; if (ShellMethodParameters.Length == parms.Length) { for (int i=0; i<ShellMethodParameters.Length; i++) if (ShellMethodParameters[i].ParameterType != parms[i].ParameterType) continue; } factoryMethod = method; } } if (factoryMethod == null) throw new Exception ("Class doesn't support factory method"); }
private static MethodInfo[] GetIntroducedMethods(System.Type type, ref string[] methodAttributes) { BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; MethodInfo[] methods = type.GetMethods(bindingAttr); if (!type.IsInterface) { methodAttributes = new string[methods.Length]; FindMethodAttributes(type, methods, ref methodAttributes, bindingAttr); ArrayList list = new ArrayList(); foreach (System.Type type2 in type.GetInterfaces()) { foreach (MethodInfo info in type.GetInterfaceMap(type2).TargetMethods) { if (!info.IsPublic && (type.GetMethod(info.Name, bindingAttr | BindingFlags.NonPublic) != null)) { list.Add(info); } } } MethodInfo[] infoArray2 = null; if (list.Count > 0) { infoArray2 = new MethodInfo[methods.Length + list.Count]; for (int i = 0; i < methods.Length; i++) { infoArray2[i] = methods[i]; } for (int j = 0; j < list.Count; j++) { infoArray2[methods.Length + j] = (MethodInfo) list[j]; } return infoArray2; } } return methods; }
private static MethodInfo getMethod( System.Type type, string name, System.Type[] paramTypes ) { // NOTE: There is a bug in Unity 4.3.3+ on Windows Phone that causes all reflection // method overloads that take a BindingFlags parameter to throw a runtime exception. // This means that we cannot have 100% compatibility between Unity 4.3.3 and prior // versions on the Windows Phone platform, and that some functionality // will unfortunately be lost. #if UNITY_EDITOR || !UNITY_WP8 var method = type.GetMethod( name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, paramTypes, null ); return method; #else var methods = type.GetMethods(); for( int i = 0; i < methods.Length; i++ ) { var info = methods[ i ]; if( info.IsStatic || info.Name != name ) continue; if( matchesParameterTypes( info, paramTypes ) ) return info; } return null; #endif }
// Attempt to find a method methodName matching the parameters given. If none is found, try to pass the entire string to a method methodName. // If neither of those things work, or no parameters are given, try to call a parameterless version of methodName. If none is found, either // methodName has no overload matching parameters given or methodName does not exist. // Returns: boolean indicating whether or not the command was handled here (true, if a method with the correct name was found, regardless of other failures). public static bool CallMethod(System.Type targetClass, string methodName, string parameters) { MethodInfo[] targetMethods = targetClass.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.FlattenHierarchy); MethodInfo[] targetInstancedMethods = new MethodInfo[0]; object main = GetMainOfClass(targetClass); if(main != null) { targetInstancedMethods = targetClass.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.FlattenHierarchy); } if(parameters != null && parameters.Length != 0) { // Try to find a static method matching name and parameters if(CallMethodMatchingParameters(null, methodName, targetMethods, parameters.SplitUnlessInContainer(' ', '\"'))) { return true; } // Try to find an instanced method matching name and parameters if a main object to invoke on exists if(main != null) { if(CallMethodMatchingParameters(main, methodName, targetInstancedMethods, parameters.SplitUnlessInContainer(' ', '\"'))) { return true; } } // Try to find a static method matching name with one string parameter MethodInfo targetMethod = targetClass.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.FlattenHierarchy, null, new System.Type[] { typeof(string) }, null); if(targetMethod != null && IsAccessible(targetMethod)) { if(IsCheat(targetMethod) && !cheats) { PrintCheatMessage(targetMethod.Name); } else { InvokeAndEchoResult(targetMethod, null, new string[] { ParseParameterListIntoType("String", parameters.SplitUnlessInContainer(' ', '\"')).ToString() }); } return true; } // Try to find a method matching name with one string parameter if a main object to invoke on exists if(main != null) { MethodInfo targetInstancedMethod = targetClass.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.FlattenHierarchy, null, new System.Type[] { typeof(string) }, null); if(targetInstancedMethod != null && IsAccessible(targetInstancedMethod)) { if(IsCheat(targetInstancedMethod) && !cheats) { PrintCheatMessage(targetInstancedMethod.Name); } else { InvokeAndEchoResult(targetInstancedMethod, main, new string[] { ParseParameterListIntoType("String", parameters.SplitUnlessInContainer(' ', '\"')).ToString() }); } return true; } } } // Try to find a static parameterless method matching name MethodInfo targetParameterlessMethod = targetClass.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.FlattenHierarchy, null, new System.Type[] { }, null); if(targetParameterlessMethod != null && IsAccessible(targetParameterlessMethod)) { if(IsCheat(targetParameterlessMethod) && !cheats) { PrintCheatMessage(targetParameterlessMethod.Name); } else { InvokeAndEchoResult(targetParameterlessMethod, null, new object[] { }); } return true; } // Try to find a parameterless method matching name if a main object to invoke on exists if(main != null) { MethodInfo targetInstancedParameterlessMethod = targetClass.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.FlattenHierarchy, null, new System.Type[] { }, null); if(targetInstancedParameterlessMethod != null && IsAccessible(targetInstancedParameterlessMethod)) { if(IsCheat(targetInstancedParameterlessMethod) && !cheats) { PrintCheatMessage(targetInstancedParameterlessMethod.Name); } else { InvokeAndEchoResult(targetInstancedParameterlessMethod, main, new object[] { }); } return true; } } // At this point no method will be invoked. Print an error message based on what has happened. if(targetMethods.Length > 0 || targetInstancedMethods.Length > 0) { bool methodWithRightNameFound = false; foreach(MethodInfo methodInfo in targetMethods) { if(methodInfo.Name == methodName && IsAccessible(methodInfo)) { methodWithRightNameFound = true; break; } } if(!methodWithRightNameFound) { foreach(MethodInfo methodInfo in targetInstancedMethods) { if(methodInfo.Name == methodName && IsAccessible(methodInfo)) { methodWithRightNameFound = true; break; } } } if(methodWithRightNameFound) { if(parameters != null && parameters.Length != 0) { Echo("No method "+methodName+" matching the parameters provided could be found."); } else { Echo("No method "+methodName+" taking no parameters could be found. Provide some parameters!"); } // In either case, the error message is handled here, so return true; return true; } } // No method matched this command, therefore indicate a failure return false; }
/// <summary> /// - Gets the methods of a type. /// </summary> /// <returns> /// - A list of methods accessible from this type. /// </returns> /// <param name='type'> /// - The type to get the methods of. /// </param> /// <param name='includeInfo'> /// - Whether or not to include each method's method info in the list. /// </param> public static string MethodsOfType(System.Type type, bool includeInfo = false) { string methods = ""; MethodInfo[] methodInfos = type.GetMethods(); for(var i = 0; i < methodInfos.Length; i++){ if(includeInfo){ methods += methodInfos[i]+"\n"; } else{ methods += methodInfos[i].Name+"\n"; } } return (methods); }
protected override void InvokeEqualsMethod(System.Type type, string[] parameters) { var method = type.GetMethods().First(m => m.Name == this.areEqual && m.GetParameters().Count() == 2); method.Invoke(null, parameters); }