01 Write C++ that speaks Java
Annotate a class and Alloy generates Hello.hpp — a typed C++ class where
Java fields are assignable members and Java methods are callable members. You implement
the native methods against it; exceptions propagate both ways.
import build.native.annotations.NativeClass;
import build.native.annotations.NativeMethod;
import build.native.annotations.NativeField;
import build.native.runtime.Alloy;
@NativeClass
public class Hello {
static final NativeLibrary LIB =
Alloy.loadLibrary(Hello.class);
/** Visible to C++ as JavaField<jint>. */
@NativeField
int greetCount = 0;
/** Implemented in Hello.cpp. */
@NativeMethod
public native String greet(String name, int n);
/** Callable from C++ as a JavaMethod. */
@NativeMethod
public String repeat(String text, int times) {
return text.repeat(times);
}
}
#include "com/example/Hello.hpp"
using namespace alloy;
using namespace java::lang;
Local<String> com::example::Hello::greet(
const Reference<String>& name, jint n) {
// Call back into Java — no receiver needed.
auto repeated = this->repeat(name, n);
auto sb = StringBuilder::create();
sb->append("Hello [");
sb->appendString(repeated);
sb->append("] from C++!");
greetCount++; // a Java field, from C++
return sb->toString();
}
/* Generated by Alloy — do not edit */
#pragma once
#include <jni.hpp>
namespace com::example {
using namespace alloy;
using namespace java::lang;
class Hello : public Object {
public:
static constexpr char className[]
= "com/example/Hello";
JavaField<jint> greetCount{"greetCount"};
JavaMethod<String(String, jint)> repeat{"repeat"};
Local<String> greet(const Reference<String>& name,
jint n);
};
}