I have names of class a and b:  string nameTypeInput = activityNamespace + "." + className; string nameTypeOutput = activityNamespace + "." + (className.Replace("Request","Response"));  Type typeInput = Type.GetType(nameTypeInput); Type typeOutput = Type.GetType(nameTypeOutput);   I have to do something like this:  var rsp = (object)request as DaDaDocsActivityBase&lt;typeInput, typeOutput&gt;;   But I have the following error:     'typeOutput' is a variable but is used like a type   What am I doing wrong?
5983
The title is kind of obscure. What I want to know is if this is possible:  string typeName = &lt;read type name from somwhere&gt;; Type myType = Type.GetType(typeName);  MyGenericClass&lt;myType&gt; myGenericClass = new MyGenericClass&lt;myType&gt;();   Obviously, MyGenericClass is described as:  public class MyGenericClass&lt;T&gt;   Right now, the compiler complains that 'The type or namespace 'myType' could not be found." There has got to be a way to do this.
65745
I have created an Apex InterfaceFactory that the user can use to get an instance of a specified implementation of an interface. For this I use the System.Type class. The actual name of the class can be set in a custom setting. I wanted to be able to pass some parameters to the constructor of the dynamically instantiated class. In short; this is the code I'm talking about:  public static MyInterface GetMyInterfaceImplementationByClassName(String settingName){     String implementationClassName;     Type t;     MyInterface implementation = null;      //get the actual class name from the custom setting     Interface_Implementations__c settings = Interface_Implementations__c.getInstance(settingName);      //just make sure there actually is a className found     if (settings != null &amp;&amp; settings.Class__c != null) {         implementationClassName = settings.Class__c;         //get the type object for the class name retrieved from the custom setting         t = Type.forName(implementationClassName);         //this line is where my question comes in; how can I pass parameters here         implementation = (MyInterface)t.newInstance();     }      return implementation; }
41562
I am trying to write a generic Parse method that converts and returns a strongly typed value from a NamedValueCollection.  I tried two methods but both of these methods are going through boxing and unboxing to get the value.  Does anyone know a way to avoid the boxing?  If you saw this in production would you not like it, how bad is it for performance?  Usuage:  var id = Request.QueryString.Parse&lt;int&gt;("id");   Attempt #1:  public static T Parse&lt;T&gt;(this NameValueCollection col, string key) {     string value = col[key];      if (string.IsNullOrEmpty(value))         return default(T);      if (typeof(T) == typeof(int))     {         //return int.Parse(value); // cannot convert int to T         //return (T)int.Parse(value); // cannot convert int to T         return (T)(object)int.Parse(value); // works but boxes     }     if (typeof(T) == typeof(long))     {         return (T)(object)long.Parse(value); // works but boxes     }     ...      return default(T); }   Attempt #2 (using reflection):  public static T Parse&lt;T&gt;(this NameValueCollection col, string key) {     string value = col[key];      if (string.IsNullOrEmpty(value))         return default(T);      try     {         var parseMethod = typeof(T).GetMethod("Parse", new Type[] { typeof(string) });          if (parseMethod == null)             return default(T);          // still boxing because invoke returns an object         var parsedVal = parseMethod.Invoke(null, new object[] { value });         return (T)parsedVal;     }     // No Proper Parse Method found     catch(AmbiguousMatchException)      {     }      return default(T); }
79010
Take the following class as an example:  class Sometype {     int someValue;      public Sometype(int someValue)     {         this.someValue = someValue;     } }   I then want to create an instance of this type using reflection:  Type t = typeof(Sometype); object o = Activator.CreateInstance(t);   Normally this will work, however because SomeType has not defined a parameterless constructor, the call to Activator.CreateInstance will throw an exception of type MissingMethodException with the message "No parameterless constructor defined for this object." Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes.
18114
I have a method with an out parameter that tries to do a type conversion. Basically:  public void GetParameterValue(out object destination) {     object paramVal = "I want to return this. could be any type, not just string.";      destination = null; // default out param to null     destination = Convert.ChangeType(paramVal, destination.GetType()); }   The problem is that usually someone would call this like:  string output; GetParameterValue(output);   This will fail because of:  destination.GetType()   destination is null, so we can't call .GetType() on it. We also can not call:  typeof(destination)   because destination is a variable name not a type name.  So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.    Just to give a bit more info, I am trying to make a utility method that will grab the output parameters of an Oracle stored procedure. The issue is that DbParameter.Value is of type object.  What would be ideal would be for the developers to do something like:  string val = GetParameterValue("parameterName");   The notable thing is that there is no casting of types. In practice, you don't know the lparam of the "equals", so I went with:  string val; GetParameterValue("parameterName", out val);   And figured within the method, I would know the destination type of the output variable. I guess that was a bad assumption. As an alternative, I also wrote the method:  public T GetParameterValue&lt;T&gt;(string paramName)   So the developers can do:  string val = GetParameterValue&lt;string&gt;("parameterName");   I find the explicit "string" declaration to be repetitive, especially since in practice, the destination if probably an object property and the oracle data type could change (think ORM):  MyObj.SomeProp = GetParameterValue&lt;MyObj.SomeProp.GetType()&gt;("parameterName");   But again, if MyObj.SomeProp is null, that .GetType() call fails. The VM has to know the type of MyObj.SomeProp, even when its null, right? or else how would it catch cast exceptions?    To partially solve my own problem, I can do:  MyObj.SomeProp = GetParameterValue&lt;typeof(MyObj).GetField("SomeProp").GetType()&gt;("parameterName");   The whole idea was to not have to explicitly use the Type in more than one place, so that if the data type changes, it only has to be changed in the destination object (MyObj.SomeProp) and in the DB. There has to be a better way...
85933
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.  Getting the field names is fairly simple, here is what a co-worker came up with:  public static List initFieldArray(String className) throws ClassNotFoundException {      Class c = Class.forName(className);     Field field[] = c.getFields();     List&lt;String&gt; classFields = new ArrayList(field.length);      for (int i = 0; i &lt; field.length; i++) {         String cf = field[i].toString();         classFields.add(cf.substring(cf.lastIndexOf(".") + 1));     }      return classFields; }   Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.  Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.
69582
Here's what I've been trying to do, in a nutshell:  class example &lt;T extends Number&gt; {     private int function(T number)     {         int x = (int) number;         ...     }     ... }   Basically, I'm trying to make it so that T is a number so I can convert it to an int inside that function. The problem is that I'm getting an "incovertible types" error, so I must be doing something wrong.
61444
I'm trying to build a Dynamic list(table) of records by selecting the Sobject and its fields.So I need to get all the fields with its API name,label,type.But I can't get the label and type.(Tried DescribeSObjectResult Class methods to get label,but it didn't help to get the label dynamically)  I tried it with the following code.  System.debug('Selection-----'+selectedObject); Map&lt;String, Schema.SObjectType&gt; gd = Schema.getGlobalDescribe();  Schema.SObjectType ctype = gd.get(selectedObject);  Map&lt;String, Schema.SobjectField&gt; fmap = ctype.getDescribe().fields.getMap();    List&lt;FieldWrap&gt; strList = new List&lt;WrapMap&gt;(); for(String s: fmap.keySet()) {     WrapMap wmp = new WrapMap();     wmp.name = s;     wmp.label = String.valueOf(fmap.get(s));     strList.add(wmp);  }   Where FieldWrap is my wrapper class with name and field of String types. I'm getting the List of API name of fields,but not the Label and type of it.Is there a way to get the label and type of field.If so, please help me.
101706
While playing with the JSON parser I encountered a use case (described below in detail) for which using JSON.deserialize(JSONResponse, SampleParent.class) method for parsing doesn't work.  Below is the use case:  public class SampleParent{      public String a {get;set;}     public String b {get;set;}     public String c {get;set;}     public String d {get;set;}     public SampleChild test {get;set;}      public SampleChild{            // in response, for this class doesn't know about the fields. in each and            // every response the fields are changing i.e. it is dynamic with no structure     }  }   How to handle such response using JSON.deserialize  and store it in Apex class variable? Actually I want to store such response in String variable.  Response :- 1  {      "a": "Sometext",       "b": "Sometext",        "c": "Sometext",         "d": "Sometext",       "test": {         "Data1": {           "score": 2         },         "Data2": {           "score1": 1         },         "Data3": {           "score1": 2         }       }   }   Response :- 2   {      "a": "Sometext",       "b": "Sometext",        "c": "Sometext",         "d": "Sometext",       "test": {         "Data50": {           "score12": 2         }              } }   Actually I want to store such response in String variable like a = '{ "Data50": {"score12": 2}}'  Can we handle this use case in Salesforce ?    Any pointers on this would be highly appreciated. Thanks in Advance.
29851
I have an error that seems common on the web,  Though i cant find a definite answer that applies to my case:  I have the following Apex code:  public with sharing class templicenseemail {      private ApexPages.standardController standardController;       public Trainee__c trainee { get; set; }     public templicenseemail(ApexPages.StandardController controller) {         this.standardController = standardController;     }      public PageReference doSomething()     {         trainee  = [SELECT Email__c,First_Name__c,Institution__c,Last_Name__c FROM Trainee__c                  WHERE Id = :ApexPages.currentPage().getParameters().get('id')];                  String whatIs = trainee.Volume_Serial_Number__c;                 integer strlen = whatIs.length();                  ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, trainee.Email__c  ));         return null;      }     }   And the following test case:  @isTest(seealldata=false)      private class Send_noti_emailsTestClass5 {          static testMethod void validateSend_noti_emails5() {              templicenseemail  MyTestcase = new templicenseemail();              // code here in the Middle              MyTestcase.doSomething();          }     }   I'm getting the following error:  Error: Compile Error: Constructor not defined: [templicenseemail].&lt;Constructor&gt;(SOBJECT:Lead) at line:      templicenseemail  MyTestcase = new templicenseemail();   Does anyone know why?
55652
public interface IBar {}  public interface IFoo : IBar {}  typeof(IFoo).BaseType == null   How can I get IBar?
81621
If I write the following class:  public class Example {        int j;       int k;        public Example(int j, int k) {            j = j;            k = k;       }        public static void main(String[] args) {            Example exm = new Example(1,2);            System.out.println(exm.j);            System.out.println(exm.k);       }  }   The program compiles, but when I run the program, the main method will print out two 0s. I know that in order to say that I want to initialize the instance variables in the constructor I have to write:  this.j = j; this.k = k;   But if I don't write it, then which variable is evaluated (or considered) in the constructor (on the left and on the write hand side of the expressions)? Is is the argument or the instance variable? Does it make a difference?  Are there other cases where the use of this is obligatory?
23661
Context Around this Code: I am making a schedulable class run each Sunday to track a couple of metrics important to the team.   Question: I am looking to consolidate DML operations and a big part of this is understanding pass by reference vs pass by value.  I want to pass the salesOps user object to the method SDREfficiencyLastWeek. I made the return type void, because I figured that I will be passing this by reference and I can make all the updates in the method without having to anything.   Why I am confused:    I read the above article and am thrown off by the following statement:  "Non-primitive data type arguments, such as sObjects, are also passed into methods by value. "   If the object is indeed passed by reference, then the query for the salesOps user in my code should be sufficient enough to edit all fields on that object without actually having to state each field in the query.  global class SDREfficientMetricsSchedulable implements Schedulable  {     global void execute(SchedulableContext sc)      {         User salesOps = [SELECT ID FROM USER WHERE id = '0056A000002Z3p9QAC'];         List&lt;String&gt; queries = new List&lt;String&gt;();          String contactsWorked_lastWeek  = 'select count(id) results from contact where LastActivityDate = last_week';         queries.add(contactsWorked_lastWeek);          String demosSet_lastWeek            = 'select count(id) results from form__c where CreatedDate = last_week';         queries.add(demosSet_lastWeek);          String demosCompleted_lastWeek  = 'select count(id) results from opportunity where (stagename = \'Unqualified Demo Completed\'  OR stagename = \'Qualified Demo Completed\' )  and RecordTypeId = \'0126A000000yudDQAQ\' and CloseDate = last_week';         queries.add(demosCompleted_lastWeek);          String qualifiedDemos_lastWeek  = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and isclosed = false and  SDR_Owner__c != null and CreatedDate = last_week';         queries.add(qualifiedDemos_lastWeek);          String closedWon_lastWeek       = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and iswon = true and  SDR_Owner__c != null and CloseDate = last_week';         queries.add(qualifiedDemos_lastWeek);            SDREfficiencyLastWeek(queries, salesOps);          update salesOps;     }       public void SDREfficiencyLastWeek(List&lt;String&gt; queries, User salesOps )     {        }  }
93772
below is my code Created a wrapper class like below  public class ResponseWrapper{     public list&lt;Account&gt; lstaccounts;     public boolean isError ;     public string errorCode;     public integer statusCode;        public ResponseWrapper(){          lstaccounts = new list&lt;Account&gt;();          isError= false;     }  }   and returning the wrapper class in the Httpget method  @RestResource(urlMapping='/accounts/*') global with sharing class AccountRestService { @HttpGet global static ResponseWrapper getAccounts() {     ResponseWrapper resWrap = new ResponseWrapper();     List&lt;Account&gt; accounts;      try {         accounts = [SELECT Id, Name FROM Account];         res.lstaccounts = accounts;     } catch (Exception e) {         RestResponse res = RestContext.response;         resWrap.isError = true;         res.responseBody = Blob.valueOf(e.getMessage()) = resWrap.errorCode;         res.statusCode = 500 = resWrap.statusCode;     }      return resWrap;   } }   but its throwing the Error message  Error: Compile Error: global methods do not support return type of ResponseWrapper at line 4 column 31
80627
I have a string variable that represents the name of a custom class. Example:   string s = "Customer";   I will need to create an arraylist of customers. So, the syntax needed is:  List&lt;Customer&gt; cust = new ..    How do I convert the string s to be able to create this arraylist on runtime?
118610
I remember seeing a while ago that there is some method in maybe the Reflection namespace that would recursively run ToString() on all of an object's properties and format it nicely for display.    Yes, I know everything I could want will be accessible through the debugger, but I'm wondering if anyone knows that command?
439
Consider:  namespace WindowsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             //int[] val = { 0, 0};             int val;             if (textBox1.Text == "")             {                 MessageBox.Show("Input any no");             }             else             {                 val = Convert.ToInt32(textBox1.Text);                 Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));                 ot1.Start(val);             }         }          private static void ReadData(object state)         {             System.Windows.Forms.Application.Run();         }          void setTextboxText(int result)         {             if (this.InvokeRequired)             {                 this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });             }             else             {                 SetTextboxTextSafe(result);             }         }          void SetTextboxTextSafe(int result)         {             label1.Text = result.ToString();         }          private static void SumData(object state)         {             int result;             //int[] icount = (int[])state;             int icount = (int)state;              for (int i = icount; i &gt; 0; i--)             {                 result += i;                 System.Threading.Thread.Sleep(1000);             }             setTextboxText(result);         }          delegate void IntDelegate(int result);          private void button2_Click(object sender, EventArgs e)         {             Application.Exit();         }     } }   Why is this error occurring?     An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)