java 中使用javascript_Java Language - Usage of Java objects in JavaScript in Nashorn | java Tutorial...

Example

It's possible to pass Java objects to Nashorn engine to be processed in Java code. At the same time, there are some JavaScript (and Nashorn) specific constructions, and it's not always clear how they work with java objects.

Below there is a table which describes behaviour of native Java objects inside JavaScript constructions.

Tested constructions:

Expression in if clause.

In JS expression in if clause doesn't have to be boolean unlike Java. It's evaluated as false for so called falsy values (null, undefined, 0, empty strings etc)

for each statement

Nashorn has a special kind of loop - for each - which can iterate over different JS and Java object.

Getting object size.

In JS objects have a property length, which returns size of an array or a string.

Results:

TypeIffor each.lengthJava nullfalseNo iterationsException

Java empty stringfalseNo iterations0

Java stringtrueIterates over string charactersLength of the string

Java Integer/Longvalue != 0No iterationsundefined

Java ArrayListtrueIterates over elementsLength of the list

Java HashMaptrueIterates over valuesnull

Java HashSettrueIterates over itemsundefined

Recommendatons:

It's advisable to use if (some_string) to check if a string is not null and not empty

for each can be safely used to iterate over any collection, and it doesn't raise exceptions if the collection is not iterable, null or undefined

Before getting length of an object it must be checked for null or undefined (the same is true for any attempt of calling a method or getting a property of Java object)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值