Scenario: I have built a DLL with Cpp which is used by a java applicaton with JNI. The DLL will call method in Java too. However, when I call CallVoidMethod, a java.lang.NullPointerException will be printed in java console.  The code is like below:  void CaptureCallback::ACallbackMethod(){     jvm-&gt;AttachCurrentThread((void **)&amp;env, NULL);     jmethodID mid= env-&gt;GetMethodID(cls, "helloWorld", "()V");     cout &lt;&lt; "The jmethodID is : " &lt;&lt; mid &lt;&lt; endl;     cout &lt;&lt; "The jobject is : " &lt;&lt; jobj &lt;&lt; endl;     cout &lt;&lt; "The env is: " &lt;&lt; env &lt;&lt; endl;     env-&gt;CallVoidMethod(obj, mid );     jvm-&gt;DetachCurrentThread(); }   What I have tried so far:   The value of jmethod is not zero. It means that I have found the method which is in Java side.(Pls correct me if I'm wrong.) Both jclass cls = env->GetObjectClass(jobj); and jclass cls = env->FindClass(absolute_path) are tried to get jclass info.   The stacktrace is so simple and it is:  Exception in thread "Thread-2"  java.lang.NullPointerException  So it's hard for me to locate the cause.  Current progress： I managed to call the helloWorld method when I put ACallbackMethod's body into the Constructor method. The constructor method is look like:  CaptureCallback::CaptureCallback(JNIEnv *p_env, jobject p_jobj){         env = p_env;         jobj = p_jobj;         jvm-&gt;AttachCurrentThread((void **)&amp;env, NULL);         jmethodID mid= env-&gt;GetMethodID(cls, "helloWorld", "()V");         cout &lt;&lt; "The jmethodID is : " &lt;&lt; mid &lt;&lt; endl;         cout &lt;&lt; "The jobject is : " &lt;&lt; obj &lt;&lt; endl;         cout &lt;&lt; "The env is: " &lt;&lt; env &lt;&lt; endl;         env-&gt;CallVoidMethod(obj, mid );            jvm-&gt;DetachCurrentThread(); }   The CaptureCallback is a class which inherits from an IDL generated header file and the CaptureCallback::ACallbackMethod is kept called from native side.The undeclared variable like env, jobj and so on are declared in CaptureCallback.h files.
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
118553
In C++ I can't use a method if I declare it after the calling method.    Does this order matter in other languages like Java or C#?
47351
Here is a little test program:   #include &lt;iostream&gt;  class Test { public:     static void DoCrash(){ std::cout&lt;&lt; "TEST IT!"&lt;&lt; std::endl; } };  int main() {     Test k;     k.DoCrash(); // calling a static method like a member method...      std::system("pause");      return 0; }   On VS2008 + SP1 (vc9) it compiles fine: the console just display "TEST IT!".  As far as I know, static member methods shouldn't be called on instanced object.   Am I wrong? Is this code correct from the standard point of view? If it's correct, why is that? I can't find why it would be allowed, or maybe it's to help using "static or not" method in templates?
45746
I am trying to use following apex class with invocable method but its not showing in process builder.  global with sharing class SlackOpportunityPublisher {      private static final String slackURL = 'https://testsalesforceapps.slack.com/';      global class Oppty {         @InvocableVariable(label='Opportunity Name')         global String opptyName;         @InvocableVariable(label='Stage')         global String stage;     }      @InvocableMethod(label='Post to Slack')     global static void postToSlack(List&lt;Oppty&gt; oppties) {         Oppty o = oppties[0]; // If bulk, only post first to avoid overloading Slack channel         Map&lt;String,Object&gt; msg = new Map&lt;String,Object&gt;();         msg.put('text', 'The following opportunity has changed:\n' + o.opptyName + '\nNew Stage: *' + o.stage + '*');         msg.put('mrkdwn', true);         String body = JSON.serialize(msg);             System.enqueueJob(new QueueableSlackCall(slackURL, 'POST', body));     }      global class QueueableSlackCall implements System.Queueable, Database.AllowsCallouts {          private final String url;         private final String method;         private final String body;          global QueueableSlackCall(String url, String method, String body) {             this.url = url;             this.method = method;             this.body = body;         }          global void execute(System.QueueableContext ctx) {             HttpRequest req = new HttpRequest();             req.setEndpoint(url);             req.setMethod(method);             req.setBody(body);             Http http = new Http();             HttpResponse res = http.send(req);         }      }  }
74634
I am trying to start share-point workflow using CSOM(Client side object model) by following means of code. But i got the following error from the line mark in comment. Please help me to figure out this error.     Error :- Cannot invoke method or retrieve property from null   object. Object returned by the following call stack is null.   "GetWorkflowDeploymentService new   Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager() "    public bool StartWorkFlow()  {     string workflowName = "UpdateDealStatus";     // connect to the workflow services via a CSOM client context    var workflowServicesManager = new WorkflowServicesManager(_sharepoint,                  _sharepoint.Web);    // connect to the deployment service    var workflowDeploymentService = workflowServicesManager.GetWorkflowDeploymentService();    // get all installed workflows   var publishedWorkflowDefinitions =    workflowDeploymentService.EnumerateDefinitions(true);             _sharepoint.Load(publishedWorkflowDefinitions);     try    {       _sharepoint.ExecuteQuery();//Error thrown from this line    }    catch (Exception ex)    {      }     // find the first workflow definition    var firstWorkflowDefinition = publishedWorkflowDefinitions.First();     // connect to the subscription service    var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();     // get all workflow associations    var workflowAssociations = workflowSubscriptionService.EnumerateSubscriptionsByDefinition(firstWorkflowDefinition.Id);     _sharepoint.Load(workflowAssociations);    _sharepoint.ExecuteQuery();     foreach (var association in workflowAssociations)    {        Console.WriteLine("{0} - {1}",        association.Id, association.Name);    }     return true; }
114098
I'm trying to write some C# code that calls a method from an unmanaged DLL.  The prototype for the function in the dll is:  extern "C" __declspec(dllexport) char *foo(void);   In C#, I first used:  [DllImport(_dllLocation)] public static extern string foo();   It seems to work on the surface, but I'm getting memory corruption errors during runtime. I think I'm pointing to memory that happens to be correct, but has already been freed.  I tried using a PInvoke code gen utility called "P/Invoke Interop Assistant".  It gave me the output:  [System.Runtime.InteropServices.DLLImportAttribute(_dllLocation, EntryPoint = "foo")] public static extern System.IntPtr foo();   Is this correct? If so, how do I convert this IntPtr to a string in C#?
31499
Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?  My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
29419
There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:  MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType); dynMethod.Invoke(this, new object[] { methodParams });   In this case, GetMethod() will not return private methods. What BindingFlags do I need to supply to GetMethod() so that it can locate private methods?
80420
In the case of languages with a C-like syntax, we declare the main() method to return an int or float value (or void).  Is it possible to declare a non-void return type from main() in Java?  If not, then why not?  Does this mean that a Java program doesn't return any value to the OS?
112048
Background  I'm using  to update some picklist values on the fly. (i.e. Every time a record is inserted/updated/deleted in Table A, I'm adding/subtracting picklist values into a MultiselectePicklist in table B).  Since,     An Apex trigger can execute a callout when the callout is invoked within a method defined as asynchronous: that is, defined with the @future keyword.   I implemented a method with the future annotation, and      For Apex code that is executed asynchronously, such as @future methods, Batch Apex jobs, or scheduled Apex jobs, getSessionId returns null.   so, I needed to pass the session Id as a parameter in the method, I implemented something like:  @future (callout=true) public static void addContactPicklistPreference(List&lt;String&gt; preferences, String sessionId){     Schema.DescribeSObjectResult sObjectDescribe = Contact.sObjectType.getDescribe();     String picklistFieldName = 'Preference__c';                    Picklist_MDT.addPicklistValues(sObjectDescribe, picklistFieldName, artists, sessionId); }  public class Picklist_MDT {      public static void addPicklistValues(Schema.DescribeSObjectResult sObjectDescribe, String picklistFieldName, List&lt;String&gt; picklistValueNames, String sessionId) {         MetadataService.MetadataPort service = createService(sessionId);         ...         }       public static MetadataService.MetadataPort createService(String sessionId) {         MetadataService.MetadataPort service = new MetadataService.MetadataPort();         service.SessionHeader = new MetadataService.SessionHeader_element();         service.SessionHeader.sessionId = sessionId;         return service;     } }   And called the addContactPicklistPreference method from trigger context passing it the UserInfo.getSessionId() value.   Problem  This worked just fine in salesforce classic but not in lightning, when it triggers in lightning I'm getting System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: INVALID_SESSION_ID.... Funny thing is that if I put a System.debug(UserInfo.getSessionId()); before calling the addContactPicklistPreference method it prints a valid session Id in both classic and lightning.  I would really appreciate any input about this.
43162
I have two different @wire methods that are calling Apex methods to get different results from two different objects.  After this information has been retrieved by each @wire respectively, I'd like to afterwards compare the results and set a few other attributes on the page.  How do I achieve this?  Should I use connectedCallback() or renderedCallback() or neither?  Is there a better way to do multiple Apex method calls then process them afterwards within the JS when the component loads?  I'm hoping there's a graceful way to accomplish this in LWC without having to chain Promises, or having to handle all of this within a single Apex method call.
110820
I'm currently making a callout to a 3rd party vendor and I'm getting a huge response. What is currently messing me up is this section:   "MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false   As you can see here, the portion at the end of the Description value is ended with backslash double quote. If I attempt to parse this via the JSONParser I get an exception. Does anyone have an recommendations on how to resolve this?  Exception Message:  System.JSONException: Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries at [line:1, column:3699]  Updated with sample Code   public class ResponseWrapper{     // fields from JSON to auto map     public Integer messageSeq;     public String Description;     public String messageTS;     public Integer messageLevel;     public Boolean isSystemMessage;     // parsing fields     private ResponseWrapper theResponse;     private JSONParser parser;      public void parse(String jsonString){         parser = JSON.createParser(jsonString);         parseJSON();     }      private void parseJSON(){            while (parser.nextToken() != null) {             if (parser.getCurrentToken() == JSONToken.START_OBJECT) {                 theResponse = (ResponseWrapper)parser.readValueAs(ResponseWrapper.class);                            }         }     } }  String responseString = '{"MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false}'; system.debug('\n\nBEFORE\n' + responseString); ****Place code in here to test such as ReplaceALL*** ResponseWrapper parser = new ResponseWrapper(); parser.parse(responseString);
61954
Note I'm running windows, the path just looks like it's linus because I typed it manually and thats how I think of paths.  I'm trying to run a java class That I have built to diagnose my connection to a databse, it references the oracle jdbc adaptor.  When I just run it without a class path:  %&gt; java DBDiagnostics &lt;connectionString&gt;   I get an exception when it reaches the following line of code:  Class.forName("oracle.jdbc.pool.OracleDataSource").newInstance();   with the following exception:  java.lang.ClassNotFoundException: oracle.jdbc.pool.OracleDataSource         at java.net.URLClassLoader$1.run(URLClassLoader.java:200)         at java.security.AccessController.doPrivileged(Native Method)         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)         at java.lang.ClassLoader.loadClass(ClassLoader.java:307)         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)         at java.lang.ClassLoader.loadClass(ClassLoader.java:252)         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)         at java.lang.Class.forName0(Native Method)         at java.lang.Class.forName(Class.java:169)         at DBDiagnostics.GetConnection(DBDiagnostics.java:43)         at DBDiagnostics.runDiagnostic(DBDiagnostics.java:29)         at DBDiagnostics.main(DBDiagnostics.java:18) Creating connection. java.sql.SQLException: No suitable driver found for lskd         at java.sql.DriverManager.getConnection(DriverManager.java:602)         at java.sql.DriverManager.getConnection(DriverManager.java:207)         at DBDiagnostics.GetConnection(DBDiagnostics.java:55)         at DBDiagnostics.runDiagnostic(DBDiagnostics.java:29)         at DBDiagnostics.main(DBDiagnostics.java:18) Veryfying connectivity to Database Exception in thread "main" java.lang.NullPointerException         at DBDiagnostics.verifyTable(DBDiagnostics.java:86)         at DBDiagnostics.verifyTable(DBDiagnostics.java:76)         at DBDiagnostics.verifyDatabseConnectivity(DBDiagnostics.java:68)         at DBDiagnostics.runDiagnostic(DBDiagnostics.java:36)         at DBDiagnostics.main(DBDiagnostics.java:18)   I assume that this is because I need to include it in the classpath.   So, I tried adding it to the classpath like this:  %&gt; java -classpath .:ojdbc6.jar DBDiagnostics &lt;connectionString&gt;   The VM just says it cant find the class:   Exception in thread "main" java.lang.NoClassDefFoundError: DBDiagnostics Caused by: java.lang.ClassNotFoundException: DBDiagnostics         at java.net.URLClassLoader$1.run(URLClassLoader.java:200)         at java.security.AccessController.doPrivileged(Native Method)         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)         at java.lang.ClassLoader.loadClass(ClassLoader.java:307)         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)         at java.lang.ClassLoader.loadClass(ClassLoader.java:252)         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) Could not find the main class: DBDiagnostics.  Program will exit.   I know this is a question I should just know the answer to, but what am I doing wrong?
102393
What would you consider to be the best exception type to throw when an extension method is called on a null instance (where the extension method does not allow it)? Since extension methods are nothing but static methods you could argue that it should be ArgumentNullException, but on the other hand they're used like instance methods so it might be more natural to use the NullReferenceException. Let's take the following example:  public static string ToInvariantString(this IFormattable value, string format) {     return value.ToString(format, CultureInfo.InvariantCulture); }   This way a NullReferenceException will be thrown if the value parameter is null.   The other example would be:  public static string ToInvariantString(this IFormattable value, string format) {     if (value == null) throw new ArgumentNullException("value");     return value.ToString(format, CultureInfo.InvariantCulture); }   EDIT: In some of the answers you have pointed out that an extension methods can be called like a static method and in those cases a null reference exception would be wrong, which is a great point, and actually one of my concerns, not sure why I forgot to mention that in the question in the first place.   Someone also pointed out that it's wrong to throw a NullReferenceException, and yes, it is. That's why I don't throw it, I just let it happen (let the CLR throw it) by not guarding the method.  I think I favor the ArgumentNullException (that's what I've use so far) but I still think there is at least room to argue for an against the NullReferenceException since it seems more natural in most places where the method is going to be used.
2745
I need to find the caller of a method. Is it possible using stacktrace or reflection?
119210
Is there a c++ equivalent of Java's  try {     ... } catch (Throwable t) {     ... }   I am trying to debug Java/jni code that calls native windows functions and the virtual machine keeps crashing.  The native code appears fine in unit testing and only seems to crash when called through jni.  A generic exception catching mechanism would prove extremely useful.