Added explicit casting function to JavaWrapper #949
Merged
+5
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
Added a function
cast(Class<T>, Object obj)
that manually performs type-wrapping to any given type to avoid problems due to type erasure.For example,
BlockState
has a such method:Where
V
is erased toObject
at runtime, so it is impossible for Rhino to determine the correct type to wrap. Consider such script:The age is a JS value due to the
+1
operation. In Rhino before, it is directly passed into thesetBlock
and cause an error due to the number is a double, and Rhino now will report:both stop the original logic from working.
Thus, an explicit type wrapping method is added in this PR as
Java.cast
, this allows users to use Rhino's type wrapping to cast a value to any type needed to pass into the method.Example Script
So, the
age
is casted tojava.lang.Integer
and then Rhino can call the method without problem.Other details
Similar functions that require such casting exist in Neoforge / Vanilla other than BlockState properties, e.g. DataComponent and Attachment. It might be ok to implement explicit support for blockstate like for DataComponent, but I think it would be better to just let users cast things to correct types directly.