highlight.js

Saturday, February 20, 2021

Javet v0.7.3

Javet v0.7.3 is released with the majority of features I expect. Let's walk through it via a few sample code snippets.

1. Dependency

Maven

<dependency>
    <groupId>com.caoccao.javet</groupId>
    <artifactId>javet</artifactId>
    <version>0.7.3</version>
</dependency>

Gradle Kotlin DSL

implementation("com.caoccao.javet:javet:0.7.3")

Gradle Groovy DSL

 implementation 'com.caoccao.javet:javet:0.7.3'

2. Samples

Hello Javet 

// Step 1: Create a V8 runtime from V8 host in try resource.
try (V8Runtime v8Runtime = V8Host.getInstance().createV8Runtime()) {
    // Step 2: Execute a string as JavaScript code and print the result to console.
    System.out.println(v8Runtime.getExecutor("'Hello Javet'").executeString()); // Hello Javet
    // Step 3: Resource is recycled automatically at the end of the try resource block.
}

Print 1 + 1

// Step 1: Create a V8 runtime from V8 host in try resource.
try (V8Runtime v8Runtime = V8Host.getInstance().createV8Runtime()) {
    // Step 2: Execute a string as JavaScript code and print the result to console.
    System.out.println("1 + 1 = " + v8Runtime.getExecutor("1 + 1").executeInteger()); // 2
    // Step 3: Resource is recycled automatically at the end of the try resource block.
}

Play with Pool and Console

// Create a Javet engine pool.
try (IJavetEnginePool javetEnginePool = new JavetEnginePool()) {
    // Get a Javet engine from the pool.
    try (IJavetEngine javetEngine = javetEnginePool.getEngine()) {
        // Get a V8 runtime from the engine.
        V8Runtime v8Runtime = javetEngine.getV8Runtime();
        // Create a Javet console interceptor.
        JavetConsoleInterceptor javetConsoleInterceptor = new JavetConsoleInterceptor(v8Runtime);
        // Register the Javet console to V8 global object.
        javetConsoleInterceptor.register(v8Runtime.getGlobalObject());
        // V8 console log is redirected to JVM console log.
        v8Runtime.getExecutor("console.log('Hello Javet from Pool');").executeVoid();
        // Unregister the Javet console to V8 global object.
        javetConsoleInterceptor.unregister(v8Runtime.getGlobalObject());
        // close() is not necessary because the Javet pool handles that.
    }
} 

You are welcome visiting https://github.com/caoccao/Javet/ for more detail. 

No comments:

Post a Comment

Cue Club 2 on Apple Silicon

It's been quite a long time for me not to play a decent snooker game since I replaced my Windows laptop with an Apple Silicon one. To be...