nashorn replace Java.type with binding - java-8

To invoke Java from JS you can use Java.type. Is there a way to bind a java class in the Bindings?
So replace:
scriptEngine.eval("Java.type('my.own.AwesomeObj')");
with something like:
Bindings bindings = new SimpleBindings();
bindings.put("AwesomeObj", my.own.AwesomeObj.class);
scriptEngine.setBindings(bingings, ScriptContext.GLOBAL_SCOPE);
I am working on a framework where I want to make a lot of classes available for the js scripts, and preferably not use a string concatenation and an eval. Currently it throws an exception with message: AwesomeObj is not a function, what makes sense.

Nashorn distinguishes a type from a java.lang.Class instance, just like Java does (in Java language, my.own.AwesomeObj is a type, while my.own.AwesomeObj.class is an instance of java.lang.Class. You can use a type to access static members, or as a constructor. You can't use a Class object for that purpose. The bad news is, you can't directly obtain the object that Nashorn uses for representing types; it's an instance of jdk.internal.dynalink.beans.StaticClass and it lives in a restricted package. However, you can evaluate it in script with
engine.eval("Java.type('my.own.AwesomeObj')");
and put the result of that in the bindings. Incidentally, within Nashorn, if you put the Class object into bindings under name AwesomeObjClass, you can use the synthetic property .static to obtain the type, e.g.:
var AwesomeObj = AwesomeObjClass.static;
In this sense, .static on a Class object is the dual of .class on a type object (.static obviously doesn't exist in Java, where types aren't reified as runtime objects).
var stringType = Java.type("java.lang.String");
var stringClass = stringType.class
print(stringClass instanceof java.lang.Class); // true
print(stringType === stringClass.static); // true
Hope this helps.

since Java 9 you can use jdk.dynalink.beans.StaticClass.forClass as it is not internal anymore:
Bindings bindings = engine.createBindings();
bindings.put("AwesomeObj", StaticClass.forClass(my.own.AwesomeObj.class));
then you can utilize the binding in the JS code with :
var awesome = new AwesomeObj();

In your top-level script of your framework do:
var AwesomeObj = Java.type("my.own.AwesomeObj");

Related

Reference to an instance method of a particular object breaks the type-safety in Java?

Does the notion of a reference to an instance method of a particular object break the type-safety in Java?
According to
https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
you can have a custom class ComparisonProvider that DOES not implement the Comparator interface, and still use an instance of this class as the second argument of the method
Arrays.sort(T[] a, Comparator c)
Sure, the implementation of your ComparisonProvider MUST have a method whose signature exactly matches the Comparator.compare() method, but that is still not an instance of Comparator, isn't it?
In essence, Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not.
This means, that we are loosing Type-safety in Java, do we?
lambda expressions and method reference don't have a predefined type, they are poly expressions, as seen here. That means that their type is derived from the context in which they are used.
In your example these both would be legal for example:
BiFunction<Person, Person, Integer> biFun = myComparisonProvider::compareByName;
Comparator<Person> comp = myComparisonProvider::compareByName;
But at the same time you can't do:
Arrays.sort(pers, biFun);
When you actually try to sort the array like this:
Arrays.sort(pers, myComparisonProvider::compareByName);
At the bytecode level that is a Comparator:
// InvokeDynamic #0:compare:(LTest$ComparisonProvider;)Ljava/util/Comparator;
Also notice that this would print true:
Comparator<Person> comp = myComparisonProvider::compareByName;
System.out.println(comp instanceof Comparator); // true
You can enable a flag : -Djdk.internal.lambda.dumpProxyClasses=/Your/Path/Here
and look at what that method reference is transformed into:
final class Test$$Lambda$1 implements java.util.Comparator
and inside it there's the compare method implementation(I've simplified it and removed some of it's code to make it a little more obvious):
public int compare(java.lang.Object, java.lang.Object);
Code:
4: aload_1
5: checkcast // class Test3$Person
8: aload_2
9: checkcast // class Test$Person
12: invokevirtual Test$ComparisonProvider.compareByName:(Test$Person;Test$Person;)I
Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not
Not exactly, it allows you to use a single method of some instance of a class as if it were implementing some functional interface.
And it doesn't add any functionality that didn't exist in Java 7 - it just gives you a short cut to writing that functionality.
For example, instead of:
Arrays.sort(someArray, someInstance::someMethod);
In Java 7 you could use anonymous class instance to write:
Arrays.sort(someArray, new Comparator<SomeType> () {
public int compare (SomeType one, SomeTypeTwo) {
return someInstance.someMethod(one,two);
}
});
As long as the instance method is accessible (i.e. public), you can use it as you see fit.
Comparator is a functional interface, which means that when requested you can pass an instance of a class implementing it, use a lambda expression that conforms to the type of single abstract method declared in it or use a method reference that also conforms to.
Java 8 Functional interface makes the difference. This tries to catch the concept of function. Afterall what is important in Comparator is not the type itself but the method (and its type) that should be provided at runtime. In pre Java 8 you need to provide a function object, while in Java 8 you can simply provide the function (just what is needed).
So for the type system everything is correct, provided that the lambdas or references you use are of the type of the method of the functional interface.

p5.js - When to declare variables using var vs this.varName

I'm still figuring out how to use p5.js. In regular java you have to declare each variable using its data type, ex. int foo = 0.
In p5, I know you can just use var foo but you can also declare variables using this.foo. If someone could clarify when is the proper time to use var and when i can use this, that would be very helpful.
For example, if I want to declare a variable inside a method, should i use var foo = thing or could I declare it using this.foo = thing? What should I use when declaring global variables or when referring to objects passed into methods?
Thanks!
First of all, p5 is not a language, it is a Javascript library, you are coding in Javascript, not p5.
Coming to your question, if you want to use some function as a data type, similar to a class in java, and want all the "instances" of that to have their own different variables, you use this. If they are just variables you use in someway but don't need to be specific for each instance, or if the function is not a constructor function and is not to be used as a data type, you will just use var then.
Again, there is no class stuff in javascript, you will have to write what is called a constructor function in order to "simulate" a java class, but be aware that a constructor function should not return anything. Here is an example of car class in java:
class car {
int speed = ___;
String model = ___;
static int numOfWheels = ___;
}
This is what it will look like in javascript (a constructor function):
function car() {
this.speed = ____;
this.model = ____;
var numOfWheels = ___;
}
If you declare a variable without this, it can be roughly compared to a static variable in a java class in the sense that it will be constant among all the instances.
So basically, at least in most cases, you will use this.varName usually inside constructor functions, i.e., functions that you will use to construct objects.
What should I use when declaring global variables or when referring to objects passed into methods?
Global variables will almost always be var something = something. When referring to objects passed into functions, just use the dot notation to refer to its properties like passedObject.someProperty
I would recommend you to learn Javascript before jumping into p5 directly, here are some resources that I found useful when I started learning Javascript-
w3 School
JavaScript Info Website
TheNewBoston

Using #BeanProperty or Create Set & Get methods using scala

In scala Using #BeanProperty or Create Set & Get methods which is the right way
In functional programming and Scala in general you should always prefer immutable objects. But if you need to change the object state, then i would stick to (g|s)etters. Cause in this case you can without changing the internal state of the object return a new object with modified state.
class MyClass(val name) {
def setName(newName: String) = new MyClass(newName)
}
This way preserves immutability and gives you setters: setName(String) and getters: obj.name
#BeanPropery is used when you need high level of interoperability with some Java code, it helps you quickly generate (g|s)etters for your code, but it has some constraints cause you cannot give the names to this methods which you would like.
Although i recomend to use case classes with copy method:
case class Person(name: String, age)
val me = Person("Alex", 23) // create an object
val afterBD = me.copy(age = 24)
The same semantics, but purely functional approach without any mutable internal state.
And as for Spring framework in Scala. I've never work with it (thank God =)), but there is a good post on this topic

c# generic orderby

In my base-repository class
i wrote this function to make possible to retrive a sorted data collection from the DB.
T is a generic defined at Class level
public abstract class RepositoryBase<T>
where T : class
The code is this:
public IList<T> GetAll<TKey>(Expression<Func<T, bool>> whereCondition, Expression<Func<T, TKey>> sortCondition, bool sortDesc = false)
{
if (sortDesc)
return this.ObjectSet.Where(whereCondition).OrderByDescending(sortCondition).ToList<T>();
return this.ObjectSet.Where(whereCondition).OrderBy(sortCondition).ToList<T>() ;
}
My goal was to introduce a generic sort parameter so that i could call the function in this way:
repo.GetAll (model=>model.field>0, model=>model.sortableField, true)
i mean that i could specify the sorting field directly via anonymous function and so using Intellisense...
Unfortunately this function doesn't work as the last code line generate errors at compile time.
I tried also to call:
repo.GetAll<Model> (model=>model.field>0, model=>model.sortableField, true)
but this don't work.
How should i write the function to meet my goal?
i'm working with EF 5, c#, .NET 4.5
You're using ObjectSet which implements IQueryable<T>. That is extended by methods on System.Linq.Queryable, which accept Expression<Func< parameters. It is correct to use those Expression parameters, as you intend for execution to occur in the database, not locally.
A Func is an anonymous delegate, a .net method.
An Expression is a tree, which may be compiled into a Func, or may be translated into Sql or something else.
You showed us a really abstract use of the method, but not an actual use of the method, or the compiler error. I suspect the error you may be making is confusing the two type parameters.
You said:
repo.GetAll<Model> (model=>model.field>0, model=>model.sortableField, true)
But this generic parameter for this method represents the type of sortableField. If sortableField isn't a Model - this is wrong.
Instead, you should be doing something like this:
Repository<Person> myRepo = new Repository<Person>();
myRepo.GetAll<DateTime>(p => p.Friends.Count() > 3, p => p.DateOfBirth, true);
If specifying the sort type breaks your intended pattern of usage, consider hiding that key by using an IOrderer: Store multi-type OrderBy expression as a property

setting private properties of classes

I have some very old code which uses reflection to set properties of objects, e.g something like this:
var properties = obj.GetType().GetProperties(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var property in properties)
{
property.SetValue(obj, lookup[property.Name]);
}
I was thinking about replacing that code to make it faster. But because the above code also allows setting private properties of an object, I'm not sure what other options there exist.
Questions:
Am I correct, that compiled expressions (using System.Linq.Expressions) and generated code (using CodeDom / Microsoft.CSharp.CSharpCodeProvider) cannot be used to set private properties?
Would that be possible using Reflection.Emit?
Would any of the mapping libraries (AutoMapper, ValueInjecter) help for this (I don't know what technology they use internally)?
Are there other options?
The open source framework Impromptu-Interface has a static method InvokeSet uses the DLR rather than reflection, and it will call private methods. It runs a little over 2 times faster than reflection in the unit speed test case, which looks similar to yours.
using ImpromptuInterface;
...
foreach(var property in properties){
ImpromptuInterface.InvokeSet(obj, property.Name, lookup[property.Name]);
}

Resources