overwrite xor in groovy - methods

I am looking for an way to overwrite xor on an groovy script.
I've created a base class for my script where a Object is defined. This object already has a method public Object xor(String var) which works like myobject^"foo". What I want is way to access this method like myobject^foo where foo handled like a normal String.

as i understand you want to do somehow that
(myobject^"foo") == (myobject^foo)
so, in your script you can redefine method getProperty() so in your script access to foo property will return "foo" string..
class A{
public Object xor(Object o){
println "xor $o"
return o
}
}
public getProperty(String key){
if(key in ['out'])return super.getProperty(key) //skip standard properties
return key
}
def myobject=new A()
assert (myobject^foo) == (myobject^"foo")
but i don't see any benefits :)

Based on your answer #daggett I found a method which handles missing properties:
public abstract class MyBaseScript extends Script implements GroovyObject {
protected class A {
public Object xor(String var) {
//do fancy stuff
return var;
}
}
protected A foo = new A();
//method which handles missing properties
public Object propertyMissing(String name) {
return name;
}
}
How do I start my scripts:
Binding binding = new Binding();
// passing parameters
binding.setVariable("arg0", arg0);
binding.setVariable("args", arg1);
// Compiler Config
CompilerConfiguration cc = new CompilerConfiguration();
ImportCustomizer ic = new ImportCustomizer();
// add some imports for e.g.
ic.addImports("java.awt.Color", "java.util.Calendar",...);
cc.addCompilationCustomizers(ic);
// set BaseClass
cc.setScriptBaseClass("de.MyBaseScript");
// execute script
GroovyClassLoader loader = new GroovyClassLoader();
shell = new GroovyShell(loader, binding, cc);
Script gscript = shell.parse(groovyScriptAsAFile);
Object o = gscript.run();

Related

Test case for constructor as i have a filter logic

I have constructor where there is filter logic and wanna test it, though writing test case for constructor is not in practice i wanna have the code coverage , have tried many links but none are explaining about handling a constructor.
public Myclass {
public Myclass(AnotherClass obj)
{
_key = obj.key;
_ID = obj.ID;
_CandidateMode = obj.CandidateMode;
if(_CandidateMode == obj.CandidateMode.numeric
{
//Dosomething
}
else
{
//Do something with special character.
}
}
}
Definitely placing logic inside a constructor is a thing to avoid. Good you know that :-) In this particular case maybe the if could go into each of the public methods of MyClass, or maybe you could use polymorphism (create MyClass or MySpecialCharacterClass base on the AnotherClass object)?
Anyway, to get to a straight answer: if you really must test constructor logic, do it like you would test any other method (in some languages it's just a static method called new, by the way).
[TestMethod]
public void is_constructed_with_numeric_candidate() {
// Given
AnotherClass obj = new AnotherClass { CandidateMode = CandidateMode.numeric };
// When
MyClass myClass = new MyClass(obj);
// Then
// assert myClass object state is correct for numeric candidate
...
}
[TestMethod]
public void is_constructed_with_special_candidate() {
// Given
AnotherClass obj = new AnotherClass { CandidateMode = CandidateMode.special };
// When
MyClass myClass = new MyClass(obj);
// Then
// assert myClass object state is correct for special candidate
...
}

Sort a list of objects based on a parameterized attribute of the object

Assuming that we have an object with the following attributes:
public class MyObject {
private String attr1;
private Integer attr2;
//...
public String getAttr1() {
return this.attr1;
}
public Integer getAttr2() {
return this.attr2;
}
}
One way of sorting a list mylist of this object, based on its attribute attr1 is:
mylist.sort(Comparator.comparing(MyObject::getAttr1));
Is it possible to use this code inside a method in a dynamic way and replace the getAttr1 part with a method that returns the getter of an attribute of the object based on its name? Something like:
public void sortListByAttr(List<MyObject> list, String attr) {
list.sort(Comparator.comparing(MyObject::getGetterByAttr(attr)));
}
The MyObject::getGetterByAttr(attr) part does not compile, I wrote it just as an example to explain my idea
I tried to implement a method with the following code new PropertyDescriptor(attr, MyObject.class).getReadMethod().invoke(new MyObject()) but It's still not possible to call a method with a parameter from the comparing method
You could add a method like
public static Function<MyObject,Object> getGetterByAttr(String s) {
switch(s) {
case "attr1": return MyObject::getAttr1;
case "attr2": return MyObject::getAttr2;
}
throw new IllegalArgumentException(s);
}
to your class, but the returned function is not suitable for Comparator.comparing, as it expects a type fulfilling U extends Comparable<? super U> and while each of String and Integer is capable of fulfilling this constraint in an individual invocation, there is no way to declare a generic return type for getGetterByAttr to allow both type and be still compatible with the declaration of comparing.
An alternative would be a factory for complete Comparators.
public static Comparator<MyObject> getComparator(String s) {
switch(s) {
case "attr1": return Comparator.comparing(MyObject::getAttr1);
case "attr2": return Comparator.comparing(MyObject::getAttr2);
}
throw new IllegalArgumentException(s);
}
to be used like
public void sortListByAttr(List<MyObject> list, String attr) {
list.sort(getComparator(attr));
}
This has the advantage that it also may support properties whose type is not Comparable and requires a custom Comparator. Also, more efficient comparators for primitive types (e.g. using comparingInt) would be possible.
You may also consider using a Map instead of switch:
private static Map<String,Comparator<MyObject>> COMPARATORS;
static {
Map<String,Comparator<MyObject>> comparators=new HashMap<>();
comparators.put("attr1", Comparator.comparing(MyObject::getAttr1));
comparators.put("attr2", Comparator.comparing(MyObject::getAttr2));
COMPARATORS = Collections.unmodifiableMap(comparators);
}
public static Comparator<MyObject> getComparator(String s) {
Comparator<MyObject> comparator = COMPARATORS.get(s);
if(comparator != null) return comparator;
throw new IllegalArgumentException(s);
}
More dynamic is only possible via Reflection, but this would complicate the code, add a lot of potential error source, with only little benefit, considering that you need only to add one line of source code for adding support for another property in either of the examples above. After all, the set of defined properties gets fixed at compile time.
You could also have a single place where this comparators would be defined:
static enum MyObjectComparator {
ATTR1("attr1", Comparator.comparing(MyObject::getAttr1));
MyObjectComparator(String attrName, Comparator<MyObject> comparator) {
this.comparator = comparator;
this.attrName = attrName;
}
private final Comparator<MyObject> comparator;
private final String attrName;
private static MyObjectComparator[] allValues = MyObjectComparator.values();
public static Comparator<MyObject> findByValue(String value) {
return Arrays.stream(allValues)
.filter(x -> x.attrName.equalsIgnoreCase(value))
.map(x -> x.comparator)
.findAny()
.orElseThrow(RuntimeException::new);
}
}
And your usage would be:
public void sortListByAttr(List<MyObject> list, String attr) {
list.sort(MyObjectComparator.findByValue(attr));
}

Java 8 Function Reference With Arguments

Trying to understand how to reference Instance functions. I've figured out how to define getters, but setters are giving me trouble. I'm not sure how to write a function for a given method signature and a given base class.
What type is Foo::setBar below?
public class Foo {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
{
//Works great!
Function<Foo, String> func1 = Foo::getBar;
//Compile error ?
Function<Foo, String> func2 = Foo::setBar;
//Compile error ?
Function<Foo, Void, String> func3 = Foo::setBar;
}
Your Function<Foo, String> func2 = Foo::setBar; is a compile error, because public void setBar(String bar) ist not a function from Foo to String, it is actually a function from String to Void.
If you want to pass the setter as method reference, you need a BiConsumer, taking a Foo and a String like
final BiConsumer<Foo, String> setter = Foo::setBar;
Or if you already got an instance of foo, you can simply use this and use a Consumer, e.g.
Foo foo = new Foo();
final Consumer<String> setBar = foo::setBar;
As setBar has a void return type, the matching functional interface single abstract method must have void return type as well. Such functional interfaces are commonly referred as "consumers". In your particular case you need to use BiConsumer which accepts a Foo object and a new bar value:
BiConsumer<Foo, String> func2 = Foo::setBar;

Java - Generic class extended by concrete class

I have a number of classes, POJO style, that shares a single functionality, say readCSV method. So I want to use a single parent (or maybe abstract, not sure if it should be) class that these POJOs can extend. Here's a pseudo-code:
(abstract) class CSVUtil {
private String[] fileHeader = null;
protected void setFileHeader(fileHeader) {
this.fileHeader = fileHeader;
}
protected List<WhateverChildClass> readCSV(String fileName) {
// read CSV using Apache Commons CSV
// and return a List of child type
List<WhateverChildClass> list = null;
// some declarations
try {
list = new ArrayList<WhateverChildClass>();
csvParser = new CSVParser(fileReader, csvFormat);
List csvRecords = csvParser.getRecords();
for (...) {
CSVRecord record = (CSVRecord) csvRecords.get(i);
WhateverChildClass childClass = new WhateverChildClass();
// loop through fields of childClass using reflection and assign
for (// all fields of childClass) {
childClass.setWhateverField(record.get(fileHeader[i]));
}
list.add(childClass);
System.out.println(p);
ps.add(p);
}
}
...
return list;
}
}
on one of the child classes, say ChildA
class ChildA extends CSVUtil {
// fields, getters, setters
}
How do I code the CSVUtil such that I can determine in runtime the child class in readCSV defined in the parent class?
Is it possible to make this method static and still be inherited?
As an alternative, is there API in Apache Commons CSV that can generally read a CSV, determine its schema, and wrap it as a generic Object (I don't know if I make sense here), and return a list of whatever that Object is ?
You want that readCSV to be a static method ?
Then, i would say that ChildA class shouldn't inherit from CSVUtil, but implement an Interface ... something like that :
public final class CSVUtil {
private CSVUtil() {
}
public static <T extends ICSV> List<T> readCSV(String filename) {
...
}
class ChildA implements ICSV

Guice : Injection and the compiler

If I declare a method :
public Car makeCar(#Named("carClassName") String carClassName){
//...
}
It seems that the compiler (eclipse) is unhappy (i.e. it won't let me call the class with no arguments).
How can I inject these parameters when I call this method , dynamically ? Is there a way to inject a call to a method ?
Solution 1: insert carClassName in the caller,
class Whatever {
private #Named("carClassName") String carClassName);
public void dosomething() {
...
Cat cat = makeCar(carclassName);
...
}
}
Solution 2: use a factory,
class CarFactory {
private #Named("carClassName") String carClassName);
public Car create() {
return makeCar(carClassName);
}
}
and inject it where needed.

Resources