So I tried to test the performance of java reflection. I want to add every value of every field in a class into a map.  public static class testClass {     String monday = &quot;Monday&quot;;     String tuesday = &quot;Tuesday&quot;;     String wednesday = &quot;Wednesday&quot;;     String thursday = &quot;Thursday&quot;;     String friday = &quot;Friday&quot;;     String saturday = &quot;Saturday&quot;;     String sunday = &quot;Sunday&quot;;     ... getter and setters ... }   public static void main(String args[]) {     noReflection();     reflection(); }  public static void noReflection() {     testClass test = new testClass();     long start = System.nanoTime();     Map myMap = new HashMap&lt;&gt;();     for (int i = 0; i &lt; RUNS; i++) {         List&lt;Integer&gt; myList = new ArrayList&lt;&gt;();         for(myDayz days: myDayz.values()) {             myList.add(days.ordinal());         }         myMap.put(myList.get(0),test.getMonday());         myMap.put(myList.get(1),test.getFriday());         myMap.put(myList.get(2),test.getSaturday());         myMap.put(myList.get(3),test.getSunday());         myMap.put(myList.get(4),test.getThursday());         myMap.put(myList.get(5),test.getTuesday());         myMap.put(myList.get(6),test.getWednesday());          myMap.clear();     }     System.out.printf(&quot;no reflection: %,d ns%n&quot;, (System.nanoTime() - start)/RUNS); }  public static void reflection() {     testClass as = new testClass();     long start = System.nanoTime();     final String stringClassName = String.class.getName();      Map myMap = new HashMap&lt;&gt;();     for (int i = 0; i &lt; RUNS; i++) {         int enumIndex = 0;         List&lt;Integer&gt; myList = getEnumsAsList(myDayz.class);         for(Field field : as.getClass().getDeclaredFields()) {             field.setAccessible(true);             String fieldTypeName = field.getGenericType().getTypeName();             try {                 Object instance = field.get(as);                 if (instance != null &amp;&amp; fieldTypeName.equals(stringClassName)) {                     myMap.put(myList.get(enumIndex),(String) instance);                     enumIndex++;                 }             } catch (IllegalAccessException e) {                 e.printStackTrace();             }         }         myMap.clear();     }     System.out.printf(&quot;reflection: %,d ns%n&quot;, (System.nanoTime() - start)/RUNS); }  private static &lt;E extends Enum&lt;E&gt;&gt; List&lt;Integer&gt; getEnumsAsList(Class&lt;E&gt; eClass) {     List&lt;Integer&gt; enumOrdinals = new ArrayList&lt;&gt;();     for (E en : EnumSet.allOf(eClass))     {         enumOrdinals.add(en.ordinal());     }     return enumOrdinals; }  private enum myDayz {     MONDAY,     TUESDAY,     WEDNESDAY,     THURSDAY,     FRIDAY,     SATURDAY,     SUNDAY }  Now what suprised me is that the non reflection code is about ~60% faster. I thought it would be ALOT faster. My question is if this is what you can expect or have i done something wrong here?
915
How do you write (and run) a correct micro-benchmark in Java?  I'm looking for some code samples and comments illustrating various things to think about.  Example: Should the benchmark measure time/iteration or iterations/time, and why?  Related:
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.
9792
Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java.  And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing...  Here's the problem I was given:  /* What is the output of the following program? */  public class Test {    public boolean equals( Test other ) {     System.out.println( "Inside of Test.equals" );     return false;   }    public static void main( String [] args ) {     Object t1 = new Test();     Object t2 = new Test();     Test t3 = new Test();     Object o1 = new Object();      int count = 0;     System.out.println( count++ );// prints 0     t1.equals( t2 ) ;     System.out.println( count++ );// prints 1     t1.equals( t3 );     System.out.println( count++ );// prints 2     t3.equals( o1 );     System.out.println( count++ );// prints 3     t3.equals(t3);     System.out.println( count++ );// prints 4     t3.equals(t2);   } }   I asserted that the output should have been two separate print statements from within the overridden equals() method: at t1.equals(t3) and t3.equals(t3).  The latter case is obvious enough, and with the former case, even though t1 has a reference of type Object, it is instantiated as type Test, so dynamic binding should call the overridden form of the method.  Apparently not.  My interviewer encouraged me to run the program myself, and lo and behold, there was only a single output from the overridden method: at the line t3.equals(t3).  My question then is, why?  As I mentioned already, even though t1 is a reference of type Object (so static binding would invoke Object's equals() method), dynamic binding should take care of invoking the most specific version of the method based on the instantiated type of the reference.  What am I missing?
84091
ok, ive a class and i pass an object as property.  the object that i pass is a List&lt;X&gt;  in my class im trying to access the Object index by reflection BUT I CAN'T!!!   Example:  this class works i just wrote down the part i want to show you and i need help.  class MyClass {     private object _recordSet;     public object RecordSet     {         get { return _recordSet; }         set { _recordSet = value; }     }      public string Draw()     {         system.reflection.Assembly asem = system.reflection.Assembly.getAssembly(_dataSource.GetType());          object instance;          instance = asem.CreateInstance(_dataSource.GetType().UnderlyingSystemType.FullName);          //to access de Count of my List         int recordcount = int.Parse(_dataSource.GetType().GetProperty("Count").GetValue(_dataSource,null));          //i need to do a          for(int cont = 0; cont &lt; recordCount; cont++)         {             _dataSource[cont].Name; // &lt;-- THIS PART IS NOT WORKING!!! because i cant access the Index Directly.... WHAT TO DO!! ???         }     } }
18923
I am trying to write a test for a trigger that is firing a future apex callout :  The trigger calls the callBillingService method from this class:  public class BillingCalloutService {     //Implement business and callout logic methods here     @Future(callout=true)     public static void callBillingService(List&lt;Id&gt; recordIds) {         List&lt;Project__c&gt; projects = [Select Id, ProjectRef__c,Billable_Amount__c from Project__c Where Id = :recordIds];          List&lt;Project__c&gt; projectsToUpdate = new List&lt;Project__c&gt;();          String username = ServiceCredentials__c.getValues('BillingServiceCredential').Username__c;         String password = ServiceCredentials__c.getValues('BillingServiceCredential').Password__c;          String auth = username + ':' + password;         String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));          for(Project__c p : projects) {              BillingServiceProxy.InvoicesPortSoap11 service = new BillingServiceProxy.InvoicesPortSoap11();             service.inputHttpHeaders_x = new Map&lt;String, String&gt;();             service.inputHttpHeaders_x.put('Authorization', 'Basic ' + encodedAuth);              BillingServiceProxy.project project = new BillingServiceProxy.project();             project.username = username;             project.password = password;             project.projectRef = p.ProjectRef__c;             project.billAmount = p.Billable_Amount__c;              if(service.billProject(project).equals('ok')){                 projectsToUpdate.add(new Project__c(ProjectRef__c = p.ProjectRef__c, Status__c = 'Billed'));             }         }         shouldIRun.stopTrigger();         upsert projectsToUpdate ProjectRef__c;     } }   Error     Methods defined as TestMethod do not support Web service callouts   Test Class  @IsTest private class BillingCalloutServiceTest {      @IsTest     private static void testBillingCalloutService() {     Account a = new Account(Name = 'Acme');     insert a;     Opportunity o = new Opportunity(Name='Test', StageName='Submitted Project', AccountId=a.Id, Amount=1000, CloseDate=Date.Today());     insert o;     Project__c p = new Project__c(Status__c='Running',Start_Date__c=Date.Today(),End_Date__c=Date.Today(),Billable_Amount__c=10000,ProjectRef__c='projectX',Opportunity__c=o.Id);     insert p;      insert new ServiceCredentials__c(Name='BillingServiceCredential',Username__c='toto', Password__c='azerty');      Test.startTest();     Test.setMock(HttpCalloutMock.class, new BillingCalloutServiceMock());       p.Status__c = 'Billable';       update p;     Test.stopTest();     // runs callout and check results     p = [select Status__c from Project__c where id =: p.id];     System.assertEquals('Billed', p.Status__c);     }  }
26439
Is there any performance difference between the for loops on a primitive array?   Assume:  double[] doubleArray = new double[300000];   for (double var: doubleArray)     someComplexCalculation(var);   or :  for ( int i = 0, y = doubleArray.length; i &lt; y; i++)    someComplexCalculation(doubleArray[i]);   Test result  I actually profiled it:  Total timeused for modern loop= 13269ms Total timeused for old loop   = 15370ms   So the modern loop actually runs faster, at least on my Mac OSX JVM 1.5.
14775
There is a case where a map will be constructed, and once it is initialized, it will never be modified again.  It will however, be accessed (via get(key) only) from multiple threads.  Is it safe to use a java.util.HashMap in this way?  (Currently, I'm happily using a java.util.concurrent.ConcurrentHashMap, and have no measured need to improve performance, but am simply curious if a simple HashMap would suffice.  Hence, this question is not "Which one should I use?" nor is it a performance question.  Rather, the question is "Would it be safe?")
91805
Short prestory. Typical problem: you have a lot of small string and you want to concatenate them all in one big string. The code like for(Integer i = 0; i &lt; smallStringsSize; i++){     bigString += smallStrings[i]; }  will solve this problem, but it has to produce a lot of unnecessary string objects that consume your heap. That is why Java has classes like StringBuilder and StringBuffer that allow you to solve this problem wihtout consuming too many memory. Thus, I decided to try to do my own StringBuilder in apex. String class has two methods that looked suitable for it:   and  . Here is the code that i used to test these methods against &quot;+=&quot; concatenantion (ready to execute in anonymous): List&lt;String&gt; chars = new List&lt;String&gt;(); List&lt;Integer&gt; charsCode = new List&lt;Integer&gt;(); Integer size = 10000; String chartToAdd = 'Ω'; for(Integer i = 0; i &lt; size; i++){     chars.add(chartToAdd);     charsCode.add(String.valueOf(chartToAdd).charAt(0)); } String joinS = '', forS = '', fromS = ''; Integer initialHeapSize = Limits.getHeapSize(); Integer initialCPUtime = Limits.getCpuTime(); System.debug('initialHeapSize ' + initialHeapSize); System.debug('initialCPUtime ' + initialCPUtime); joinS = String.join(chars, ''); Integer joinHeapSize = Limits.getHeapSize() - initialHeapSize; Integer joinCPUtime = Limits.getCpuTime() - initialCPUtime; System.debug('-------- String.join ---------'); System.debug('joinHeapSize ' + joinHeapSize); System.debug('joinCPUtime ' + joinCPUtime); for(Integer i = 0; i &lt; size; i++){     forS += chars[i]; } Integer forHeapSize = Limits.getHeapSize() - joinHeapSize - initialHeapSize; Integer forCPUtime = Limits.getCpuTime() - joinCPUtime - initialCPUtime; System.debug('-------- for each += ---------'); System.debug('forHeapSize ' + forHeapSize); System.debug('forCPUtime ' + forCPUtime); fromS = String.fromCharArray(charsCode); Integer fromHeapSize = Limits.getHeapSize() - forHeapSize - joinHeapSize - initialHeapSize; Integer fromCPUtime = Limits.getCpuTime() - forCPUtime - joinCPUtime - initialCPUtime; System.debug('-------- String.fromCharArray ---------'); System.debug('fromHeapSize ' + fromHeapSize); System.debug('fromCPUtime ' + fromCPUtime); System.debug(''); System.debug('-------- strings ----------'); System.debug('joins ' + joins); System.debug('fors ' + fors); System.debug('fromS ' + fromS);  The result of this code execution:  initialHeapSize 161166 initialCPUtime 242 -------- String.join --------- joinHeapSize 10016 joinCPUtime 17 -------- for each += --------- forHeapSize 10024 forCPUtime 48 -------- String.fromCharArray --------- fromHeapSize 10016 fromCPUtime 5  As you can see, the heap size for each approach is so close to 10 kilobytes, what is a size of the string of 10 000 characters (size) if each character takes only one byte. In case of creating 10 000 additional string objects, the heap size would be a bit more than 50 megabytes (10 000 * (1 + 10 000)/2). Taking into consideration the above,  Does not the '+=' concatenation create any additional string objects that devour your heap? Did not I miss anything? I am so amazed.  As you see, I use Omega 'Ω' as a chartToAdd. It has  the high-surrogate code point equals to 937, that needs at least 2 bytes to be encoded. How can 10 000 Omegas consume only 10 000 bytes of the heap size?  What weightful reasons Salesforce has that they do not to add the character data type? Any ideas?
92671
public class ExampleClass {       public static void publishCaseUpdateNotifications(List&lt;Case&gt; cases) {     List&lt;Case_Updated__e&gt; notifications = new List&lt;Case_Updated__e&gt;();     for (Case c: cases) {         notifications.add(new Case_Updated__e(             Case__c = (String)c.Id,             CreatedByName__c = UserInfo.getName(),             CaseNumber__c = c.CaseNumber         ));     }       List&lt;Database.SaveResult&gt; results = EventBus.publish(notifications);      for (Database.SaveResult result : results) {         if (!result.isSuccess()) {             for (Database.Error error : result.getErrors()) {                 System.debug('Error returned: ' +                     error.getStatusCode() +' - '+                     error.getMessage());             }         }       }      }    }   My Test Class: getting error   @isTest   public class ExampleTestClass {    @isTest   static void testClassforExample(){         Case testcase = new Case(Subject ='Test',);      list&lt;Case_Updated__e&gt; caseUpdate =      ExampleClass.publishCaseUpdateNotifications(testcase );       }      }   My Error is Method does not exist or incorrect signature: void publishCaseUpdateNotifications(Case) from the type ExampleTestClass   Please suggest me how to resolve this error.     trigger Cases on Case (after insert) { if(Trigger.isAfter) {     System.debug('I will be replaced shortly!'); }  }   Do we need test class for above trigger. Please suggest me too
65547
See also      Not a major issue, just annoying as I don't want my class to ever be instantiated without the particular arguments.  #include &lt;map&gt;  struct MyClass {     MyClass(int t); };  int main() {     std::map&lt;int, MyClass&gt; myMap;     myMap[14] = MyClass(42); }   This gives me the following g++ error:     /usr/include/c++/4.3/bits/stl_map.h:419: error: no matching function for call to ‘MyClass()’   This compiles fine if I add a default constructor; I am certain it's not caused by incorrect syntax.
99253
I like how Java has a Map where you can define the types of each entry in the map, for example &lt;String, Integer&gt;.   What I'm looking for is a type of collection where each element in the collection is a pair of values.  Each value in the pair can have its own type (like the String and Integer example above), which is defined at declaration time.    The collection will maintain its given order and will not treat one of the values as a unique key (as in a map).    Essentially I want to be able to define an ARRAY of type &lt;String,Integer&gt; or any other 2 types.    I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose.    I also realize that I could use a 2D array, but because of the different types I need to use, I'd have to make them arrays of OBJECT, and then I'd have to cast all the time.    I only need to store pairs in the collection, so I only need two values per entry.  Does something like this exist without going the class route?  Thanks!
57677
Does creating an object using reflection rather than calling the class constructor result in any significant performance differences?
18175
Say I am iterating over a Map in Java... I am unclear about what I can to that Map while in the process of iterating over it. I guess I am mostly confused by this warning in the Javadoc for the Iterator interface remove method:     [...] The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.   I know for sure that I can invoke the remove method without any issues. But while iterating over the Map collection, can I:   Change the value associated with a key with the Map class put method (put with an existing key)? Add a new entry with the Map class put method (put with a new key)? Remove an entry with the Map class remove method?   My guess is that I can probably safely do #1 (put to an existing key) but not safely do #2 or #3.  Thanks in advance for any clarification on this.
20509
I have a small code example I want to include in the Javadoc comment for a method.    /**  * -- ex: looping through List of Map objects --  * &lt;code&gt;  * for (int i = 0; i &lt; list.size(); i++) {  *      Map map = (Map)list.get(i);  *      System.out.println(map.get("wordID"));  *      System.out.println(map.get("word"));  * }  * &lt;/code&gt;  *   * @param query - select statement  * @return List of Map objects  */   The problem is the code example shows up in the Javadoc with no line breaks making it hard to read.    -- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); }  Parameters query - - select statement  Returns: List of Map objects    I guess I am wrong in assuming the code tag would handle line breaks.  What is the best way to format code examples in Javadoc comments ?
89434
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code:  public void test1() {     // Throw an exception for testing purposes     throw new ArgumentException("test1"); }  void test2() {     try     {         MethodInfo mi = typeof(Program).GetMethod("test1");         mi.Invoke(this, null);     }     catch (TargetInvocationException tiex)     {         // Throw the new exception         throw tiex.InnerException;     } }
118759
Question  I'm writing some code that needs to be able to get the values of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?  If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.  Code  // Finds calling method from class that called into this one public class SomeClass {     public static void FindMethod()     {         for (int i = 1; i &lt; frameCount; i++)         {             var frame = new StackFrame(i);             var methodInfo = frame.GetMethod();             if (methodInfo.DeclaringType != this.GetType())             {                 string methodName = frame.GetMethod().Name;                 var paramInfos = methodInfo.GetParameters();                  // Now what?? How do I get the values from the paramInfos                  break;             }             else if (i == frameCount - 1)             {                 throw new TransportException("Couldn't find method name");             }         }     } }
88076
This is what I've come up with as a method on a class inherited by many of my other classes. The idea is that it allows the simple comparison between properties of Objects of the same Type.  Now, this does work - but in the interest of improving the quality of my code I thought I'd throw it out for scrutiny. How can it be better/more efficient/etc.?  /// &lt;summary&gt; /// Compare property values (as strings) /// &lt;/summary&gt; /// &lt;param name="obj"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public bool PropertiesEqual(object comparisonObject) {      Type sourceType = this.GetType();     Type destinationType = comparisonObject.GetType();      if (sourceType == destinationType)     {         PropertyInfo[] sourceProperties = sourceType.GetProperties();         foreach (PropertyInfo pi in sourceProperties)         {             if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null &amp;&amp; destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))             {                 // if both are null, don't try to compare  (throws exception)             }             else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))             {                 // only need one property to be different to fail Equals.                 return false;             }         }     }     else     {         throw new ArgumentException("Comparison object must be of the same type.","comparisonObject");     }      return true; }