Skip to content

Instantly share code, notes, and snippets.

@MasseGuillaume
Created April 26, 2012 15:51
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MasseGuillaume/2500529 to your computer and use it in GitHub Desktop.
Save MasseGuillaume/2500529 to your computer and use it in GitHub Desktop.
Insert key value pair in a std::map then output in a java HashMap
// @author Guillaume Masse
#include "JHashMap.h"
#include <string>
using namespace std;
void JHashMap::insert( std::string key, std::string value )
{
map.insert( pair<string,string>( key, value ) );
}
jobject JHashMap::toJObject( JNIEnv* env, jclass )
{
jclass clazz = env->FindClass("java/util/HashMap");
jmethodID init = env->GetMethodID(clazz, "<init>", "()V");
jobject propertyMap = env->NewObject(clazz, init);
jmethodID putMethod = env->GetMethodID(
clazz,
"put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"
);
for( auto it = map.begin(); it != map.end(); ++it )
{
jstring key = (*env).NewStringUTF( (*it).first.c_str() );
jstring value = (*env).NewStringUTF( (*it).second.c_str() );
(*env).CallVoidMethod(
propertyMap,
putMethod,
key,
value
);
}
return propertyMap;
}
#pragma once
// @author Guillaume Masse
#include <map>
#include <string>
#include "jni.h"
class JHashMap
{
public:
void insert( std::string key, std::string value );
jobject toJObject(JNIEnv *, jclass);
private:
std::map< std::string, std::string > map;
};
@piotrros
Copy link

Can someone tell me how to call toJObject function and what should I give as "jclass" parameter? I'm clueless.

@piotrros
Copy link

Ok, figured it out. Just removed jclass parameter :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment