/*******************************/ /// <summary> /// Creates an instance of a received Type. /// </summary> /// <param name="classType">The Type of the new class instance to return.</param> /// <returns>An Object containing the new instance.</returns> public static object CreateNewInstance(System.Type classType) { if (classType == null) throw new Exception("Class not found"); object instance = null; System.Type[] constructor = new System.Type[] {}; ConstructorInfo[] constructors = null; constructors = classType.GetConstructors(); if (constructors.Length == 0) throw new UnauthorizedAccessException(); else { for (int i = 0; i < constructors.Length; i++) { ParameterInfo[] parameters = constructors[i].GetParameters(); if (parameters.Length == 0) { instance = classType.GetConstructor(constructor).Invoke(new Object[] {}); break; } else if (i == constructors.Length - 1) throw new MethodAccessException(); } } return instance; }
/// <summary> /// Determines which constructor implementation should be used from a given <see cref="IDependencyContainer"/> instance. /// </summary> /// <param name="targetType">The target type that contains list of constructors to be resolved.</param> /// <param name="container">The dependency container that holds the current set of dependencies.</param> /// <returns>An implementation that can instantiate the object associated with the constructor.</returns> public virtual IImplementation<ConstructorInfo> ResolveFrom(System.Type targetType, IDependencyContainer container) { IImplementation<ConstructorInfo> result = null; var constructors = new List<IImplementation<ConstructorInfo>>(); foreach(var constructor in targetType.GetConstructors()) { var constructorCall = CreateConstructorCall(constructor); constructors.Add(constructorCall); } var bestParameterCount = 0; foreach (var constructor in constructors) { var missingDependencies = constructor.GetMissingDependencies(container); var missingItems = new List<IDependency>(missingDependencies); var hasMissingDependencies = missingDependencies == null || missingItems.Count > 0; if (hasMissingDependencies) continue; var targetConstructor = constructor.Target; var parameters = targetConstructor.GetParameters(); var parameterCount = parameters.Length; if (result == null || parameterCount > bestParameterCount) { result = constructor; bestParameterCount = parameterCount; } } return result; }
/// <summary> /// Creates an instance of a received Type /// </summary> /// <param name="classType">The Type of the new class instance to return</param> /// <returns>An Object containing the new instance</returns> public static System.Object CreateNewInstance(System.Type classType) { System.Reflection.ConstructorInfo[] constructors = classType.GetConstructors(); if (constructors.Length == 0) return null; System.Reflection.ParameterInfo[] firstConstructor = constructors[0].GetParameters(); int countParams = firstConstructor.Length; System.Type[] constructor = new System.Type[countParams]; for( int i = 0; i < countParams; i++) constructor[i] = firstConstructor[i].ParameterType; return classType.GetConstructor(constructor).Invoke(new System.Object[]{}); }
public QueryModelDescription (System.Type aModel, QueryModelAttribute aDescription) { if (aModel == null) throw new NullReferenceException ("QueryModelDescription: Model type can't be null"); if (aDescription == null) throw new NullReferenceException ("QueryModelDescription: Attribute must be specified"); foreach (ConstructorInfo info in aModel.GetConstructors()) if (info.GetParameters().Length == 1) if (TypeValidator.IsCompatible(info.GetParameters()[0].ParameterType, typeof(MappingsImplementor)) == true) { constructor = info; break; } if (constructor == null) throw new NotImplementedException ("QueryModelDescription: QueryImplementor needs public .ctor (MappingsImplementor)"); model = aModel; definition = aDescription; }
/// <summary> /// Finds the constructor that takes the parameters. /// </summary> /// <param name="type">The <see cref="System.Type"/> to find the constructor in.</param> /// <param name="types">The <see cref="IType"/> objects to use to find the appropriate constructor.</param> /// <returns> /// An <see cref="ConstructorInfo"/> that can be used to create the type with /// the specified parameters. /// </returns> /// <exception cref="InstantiationException"> /// Thrown when no constructor with the correct signature can be found. /// </exception> public static ConstructorInfo GetConstructor(System.Type type, IType[] types) { ConstructorInfo[] candidates = type.GetConstructors(AnyVisibilityInstance); foreach (ConstructorInfo constructor in candidates) { ParameterInfo[] parameters = constructor.GetParameters(); if (parameters.Length == types.Length) { bool found = true; for (int j = 0; j < parameters.Length; j++) { bool ok = parameters[j].ParameterType.IsAssignableFrom( types[j].ReturnedClass); if (!ok) { found = false; break; } } if (found) { return constructor; } } } throw new InstantiationException(FormatConstructorNotFoundMessage(types), null, type); }
/// <summary> /// Creates a new property attribute instance. /// </summary> /// <returns>An unbound property attribute.</returns> /// <param name="propertyAttributeType">Property attribute type.</param> /// <param name="constructorArguments">Constructor arguments.</param> public static PropertyAttribute CreateNew( System.Type propertyAttributeType, params object[] constructorArguments ) { // try to find the matching constructor ConstructorInfo constructor = null; System.Type[] suppliedArgTypes = (from param in constructorArguments select param == null ? typeof(object) : param.GetType()).ToArray(); foreach (ConstructorInfo ctor in propertyAttributeType.GetConstructors()) { ParameterInfo[] ctorParams = ctor.GetParameters(); System.Type paramArrayType = ( ctorParams.LastOrDefault() != null && ctorParams.Last().GetCustomAttributes(typeof(System.ParamArrayAttribute), false).Length > 0 ) ? ctorParams.Last().ParameterType : null; constructor = ctor; // first check explicitly supplied arguments for (int i=0; i<suppliedArgTypes.Length; ++i) { // if there are more supplied arguments than parameter types, see if they match param type if ( i >= ctorParams.Length && (paramArrayType == null || !paramArrayType.IsAssignableFrom(suppliedArgTypes[i])) ) { constructor = null; continue; } // if supplied argument type is mismatch, then constructor is a bad match if ( !ctorParams[i].ParameterType.IsAssignableFrom(suppliedArgTypes[i]) || (suppliedArgTypes[i] == null && !ctorParams[i].ParameterType.IsClass) ) { constructor = null; } } // if candidate is a match, see if it has any further parameters if (constructor != null && ctorParams.Length > suppliedArgTypes.Length) { List<object> newArgs = new List<object>(constructorArguments); for (int i=suppliedArgTypes.Length; i<ctorParams.Length; ++i) { // candidate is a mistmatch if the argument is not optional, or is not the params argument if (!ctorParams[i].IsOptional && !(paramArrayType != null && i == ctorParams.Length - 1)) { constructor = null; } else if (ctorParams[i].IsOptional) { newArgs.Add(ctorParams[i].DefaultValue); } } // if candidate is still a match, append missing arguments if (constructor != null) { constructorArguments = newArgs.ToArray(); } } // break out if the candidate is still valid if (constructor != null) { break; } } if (constructor == null) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.Type type in suppliedArgTypes) { sb.AppendFormat(", {0}", type); } throw new System.ArgumentException( "constructorArguments", string.Format( "No constructor found for {0} matching method signature [{1}].", propertyAttributeType, sb.Length > 0 ? sb.ToString().Substring(2) : "" ) ); } return constructor.Invoke(constructorArguments) as PropertyAttribute; }
/// <summary> /// Finds the constructor that takes the parameters. /// </summary> /// <param name="type">The <see cref="System.Type"/> to find the constructor in.</param> /// <param name="types">The <see cref="IType"/> objects to use to find the appropriate constructor.</param> /// <returns> /// An <see cref="ConstructorInfo"/> that can be used to create the type with /// the specified parameters. /// </returns> /// <exception cref="InstantiationException"> /// Thrown when no constructor with the correct signature can be found. /// </exception> public static ConstructorInfo GetConstructor( System.Type type, IType[] types ) { ConstructorInfo[] candidates = type.GetConstructors( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); foreach( ConstructorInfo constructor in candidates ) { ParameterInfo[] parameters = constructor.GetParameters(); if( parameters.Length == types.Length ) { bool found = true; for( int j = 0; j < parameters.Length; j++ ) { bool ok = parameters[ j ].ParameterType.IsAssignableFrom( types[ j ].ReturnedClass ); if( !ok ) { found = false; break; } } if( found ) { return constructor; } } } throw new InstantiationException( "no appropriate constructor in class: ", null, type ); }
public static void DisposCtor(System.Type type, Dictionary<string, ClassMethodInfo> cmfDict) { string fullNamePrefix = type.Namespace + "." + type.Name + "." + "New"; string newStr = "New"; ConstructorInfo[] ctorArray = type.GetConstructors(BindingFlags.Instance | BindingFlags); foreach (ConstructorInfo cInfo in ctorArray) { ClassMethodInfo ctorCmf = !cmfDict.ContainsKey(newStr) ? new ClassMethodInfo() : cmfDict[newStr]; ctorCmf.fullName = fullNamePrefix + newStr; ctorCmf.className = type.Name; ctorCmf.name = newStr; ctorCmf.returnName = type.Name; ctorCmf.isStatic = true; cmfDict[newStr] = ctorCmf; ctorCmf.overrideList.Add(DisposMethodArgs(cInfo.GetParameters())); } }
private System.Type CreateUncachedProxyType(System.Type baseType, System.Type[] baseInterfaces) { var currentDomain = AppDomain.CurrentDomain; var typeName = string.Format("{0}Proxy", baseType.Name); var assemblyName = string.Format("{0}Assembly", typeName); var moduleName = string.Format("{0}Module", typeName); var name = new AssemblyName(assemblyName); //rippo: the [*]commented lines allow the serialize of the assembly containing the proxy //you can then run PEVERIFY to check the IL for type safety //[*]const AssemblyBuilderAccess access = AssemblyBuilderAccess.RunAndSave; const AssemblyBuilderAccess access = AssemblyBuilderAccess.Run; var assemblyBuilder = currentDomain.DefineDynamicAssembly(name, access); //[*]var moduleBuilder = assemblyBuilder.DefineDynamicModule("generatedAssembly.dll", "generatedAssembly.dll", true); var moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName); const TypeAttributes typeAttributes = TypeAttributes.AutoClass | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.BeforeFieldInit; var interfaces = new HashSet<System.Type>(); interfaces.Merge(baseInterfaces); var parentType = baseType; if (baseType.IsInterface) { parentType = typeof (ProxyDummy); interfaces.Add(baseType); } var computedInterfaces = interfaces.ToArray(); foreach (var interfaceType in computedInterfaces) { interfaces.Merge(GetInterfaces(interfaceType)); } interfaces.Add(typeof (ISerializable)); var typeBuilder = moduleBuilder.DefineType(typeName, typeAttributes, parentType, interfaces.ToArray()); var implementor = new ProxyImplementor(); implementor.ImplementProxy(typeBuilder); var interceptorField = implementor.InterceptorField; AddSerializationSupport(typeBuilder); var constructors = baseType.GetConstructors(); foreach (var constructorInfo in constructors) { var constructorBuilder = DefineConstructor(typeBuilder, constructorInfo); DefineSerializationConstructor(typeBuilder, interceptorField, constructorBuilder, constructorInfo); } ImplementGetObjectData(baseType, baseInterfaces, typeBuilder, interceptorField); foreach (var method in GetProxiableMethods(baseType, interfaces).Where(method => method.DeclaringType != typeof(ISerializable))) { ProxyMethodBuilder.CreateProxiedMethod(interceptorField, method, typeBuilder); } var proxyType = typeBuilder.CreateType(); //[*]assemblyBuilder.Save("generatedAssembly.dll"); return proxyType; }
public static object InstantiateClassByType(System.Type type) { object obj = null; //cant call the entry method if the assembly is null ConstructorInfo[] constructors = type.GetConstructors(); foreach (ConstructorInfo constructor in constructors) { if (constructor.GetParameters().Length == 0) { obj = constructor.Invoke(BindingFlags.CreateInstance, null, new object[] {}, null); break; } } return obj; }
private RubyMethod FindCLRMethod(string methodId, System.Type clrtype) { BindingFlags flags = BindingFlags.Instance | BindingFlags.Public; if (this._type == Type.IClass) { // static methods if (methodId == "new") { if (clrtype.IsSubclassOf(typeof(System.Delegate))) { return new RubyMethod(new DelegateConstructor(clrtype), 0, Access.Public, this); } else { ConstructorInfo[] ci = clrtype.GetConstructors(); if (ci == null || ci.Length == 0) return null; MethodBase[] mi = new MethodBase[ci.Length]; System.Array.Copy(ci, mi, ci.Length); return new RubyMethod(new MultiMethod(mi), -1, Access.Public, this); } } else if (methodId == "allocator") { return new RubyMethod(Methods.rb_class_allocate_instance.singleton, 0, Access.Private, this); } else if (methodId == "[]") { // instantiate a generic type // ruby: type = ns::List[System::Int32] if (clrtype.IsGenericType) { // clrtype is Type`n+Inner but we are looking for Type`n+Inner`n // we need to strip generic arguments from the name, but supply // them to the GenericTypeGetter return new RubyMethod( new GenericTypeGetter( clrtype.Assembly, clrtype.GetGenericTypeDefinition().FullName, clrtype.GetGenericArguments()), -1, Access.Public, this); } else { return new RubyMethod( new GenericTypeGetter(clrtype.Assembly, clrtype.FullName, null), -1, Access.Public, this); } } flags = BindingFlags.Static | BindingFlags.Public; } bool is_setter = false; // methods ending with "=" are expected to be either // field or property setters if (methodId.EndsWith("=")) { is_setter = true; methodId = methodId.Substring(0, methodId.Length - 1); } // default member access, an Indexer in C# if (methodId == "[]") { object[] attributes = clrtype.GetCustomAttributes( typeof(System.Reflection.DefaultMemberAttribute), true); if (attributes.Length > 0) { methodId = ((DefaultMemberAttribute)attributes[0]).MemberName; } } MemberInfo[] members = clrtype.GetMember(methodId, flags); if (members.Length == 0) { // we didn't find a member with the exact name // but we still need to check for nested types with // additional type parameters string genericNestedId = methodId + "`"; foreach (System.Type nested in clrtype.GetNestedTypes(flags)) { if (nested.Name.StartsWith(genericNestedId)) { return new RubyMethod( new ValueMethod( new GenericContainer( clrtype.Assembly, clrtype.Name + "+" + methodId, clrtype.GetGenericArguments())), 0, Access.Public, this); } } return null; } if (members[0] is MethodBase) { if (is_setter) return null; MethodBase[] methods = new MethodBase[members.Length]; System.Array.Copy(members, methods, members.Length); return new RubyMethod(new MultiMethod(methods), -1, Access.Public, this); } if (members[0] is PropertyInfo) { // not all the property overloads may have the getter/setter // we're looking for, so we maintain a count and resize // the methods array later if necessary int count = 0; MethodBase[] methods = new MethodBase[members.Length]; foreach (PropertyInfo pi in members) { MethodInfo method = is_setter ? pi.GetSetMethod() : pi.GetGetMethod(); if (method != null) methods[count++] = method; } if (count == 0) return null; if (count < members.Length) System.Array.Resize(ref methods, count); return new RubyMethod(new MultiMethod(methods), -1, Access.Public, this); } FieldInfo field = members[0] as FieldInfo; if (field != null) { if (is_setter) return new RubyMethod(new FieldSetter(field), 1, Access.Public, this); else return new RubyMethod(new FieldGetter(field), 0, Access.Public, this); } //EventInfo eventinfo = members[0] as EventInfo; //if (eventinfo != null) //{ // return ...; //} // nested types System.Type type = members[0] as System.Type; if (type != null) { // see section 10.7.1 of ECMA if (type.IsGenericTypeDefinition) type = type.MakeGenericType(clrtype.GetGenericArguments()); return new RubyMethod( new NestedTypeGetter(Load(type, null, false)), 0, Access.Public, this); } return null; }
public Component CreateComponent(List<Control> controlList, System.Type type) { System.Type[] typeArray = new System.Type[] { type }; ConstructorInfo[] constructors = type.GetConstructors(); object[] parameters = new object[0]; Component component = (Component) constructors[0].Invoke(parameters); controlList.Add((Control) component); return component; }
public System.Object NewInstanceOf(System.Type clazz) { System.Reflection.ConstructorInfo constructor = null; constructor = classPool.GetConstrutor(OdbClassUtil.GetFullName(clazz)); if (constructor == null) { // Checks if exist a default constructor - with no parameters constructor = clazz.GetConstructor(Type.EmptyTypes); //UPGRADE_ISSUE: Method 'java.lang.reflect.AccessibleObject.setAccessible' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangreflectAccessibleObject'" //c by cristi //constructor.setAccessible(true); if(constructor!=null) { classPool.AddConstrutor(OdbClassUtil.GetFullName( clazz), constructor); } } if (constructor != null) { System.Object o = constructor.Invoke(new System.Object[0]); return o; } if (clazz.IsValueType) { return Activator.CreateInstance(clazz); } else { // else take the constructer with the smaller number of parameters // and call it will null values // @TODO Put this info in cache ! if (OdbConfiguration.IsDebugEnabled(LogId)) { DLogger.Debug(clazz + " does not have default constructor! using a 'with parameter' constructor will null values"); } System.Reflection.ConstructorInfo[] constructors = clazz.GetConstructors(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.DeclaredOnly); if (clazz.IsInterface) { //@TODO This is not a good solution to manage interface return null; } if (constructors.Length == 0) { throw new ODBRuntimeException(NeoDatisError.ClassWithoutConstructor.AddParameter(clazz.AssemblyQualifiedName)); } int numberOfParameters = 1000; int bestConstructorIndex = 0; for (int i = 0; i < constructors.Length; i++) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" if (constructors[i].GetParameters().Length < numberOfParameters) { bestConstructorIndex = i; } } constructor = constructors[bestConstructorIndex]; //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" System.Object[] nulls = new System.Object[constructor.GetParameters().Length]; for (int i = 0; i < nulls.Length; i++) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //m by cristi if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Int32")) { nulls[i] = 0; } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Int64")) { nulls[i] = 0; } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Int16")) { nulls[i] = System.Int16.Parse("0"); } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //main by cristi if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.SByte")) { nulls[i] = System.SByte.Parse("0"); } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //m by cristi if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Single")) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" nulls[i] = System.Single.Parse("0"); } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //m by cristi if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Double")) { //UPGRADE_TODO: The differences in the format of parameters for constructor 'java.lang.Double.Double' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" nulls[i] = System.Double.Parse("0"); } else { nulls[i] = null; } } } } } } } System.Object object_Renamed = null; //UPGRADE_ISSUE: Method 'java.lang.reflect.AccessibleObject.setAccessible' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangreflectAccessibleObject'" //c by cristi //constructor.setAccessible(true); try { object_Renamed = constructor.Invoke(nulls); } catch (System.Exception e2) { throw new ODBRuntimeException(NeoDatisError.NoNullableConstructor.AddParameter("[" + DisplayUtility.ObjectArrayToString(constructor.GetParameters()) + "]").AddParameter(clazz.AssemblyQualifiedName), e2); } return object_Renamed; } }
/// <summary> /// Creates an instance of a received Type. Looks for a constructor with no parameters /// </summary> /// <param name="classType">The Type of the new class instance to return.</param> /// <returns>An Object containing the new instance.</returns> public static object CreateNewInstance(System.Type classType) { object instance = null; switch (classType.FullName) { case "System.Char": case "System.Byte": case "System.Int16": case "System.Int32": case "System.Int64": case "System.UInt16": case "System.UInt32": case "System.UInt64": case "System.DateTime": case "System.Boolean": case "System.Decimal": case "System.Double": case "System.Single": case "System.String": case "string": case "object": case "System.Object": return CreateNewInstance(classType, ""); default: System.Type[] constructor = new System.Type[]{}; System.Reflection.ConstructorInfo[] constructors = null; constructors = classType.GetConstructors(); if (constructors.Length == 0) throw new System.UnauthorizedAccessException(); else { for(int i = 0; i < constructors.Length; i++) { System.Reflection.ParameterInfo[] parameters = constructors[i].GetParameters(); if (parameters.Length == 0) { instance = classType.GetConstructor(constructor).Invoke(new object[]{}); break; } else if (i == constructors.Length -1) { throw new System.MethodAccessException(); } } } return instance; } }