Porting the function from Kotlin to Java

Hello! I need to port this function from Kotlin to Java

open val values: List<Value> get() = javaClass.declaredFields.map { valueField ->
    valueField.isAccessible = true
    valueField[this]
}.filterIsInstance<Value>()

(looks for every method in class and returns all the methods with instance of Value)

I tried alot, but still can’t port it! I’ll be grateful for any of your’s help <З

What problem are you specifically facing?

I wan’t to make the function on JAVA language from existing KOTLIN language function

So, now I made this function:

public List<Value> getValues() {
    Collection<Object> collection = new ArrayList<>();
    for (Object o : Arrays.stream(this.getClass().getFields()).toArray()) {
        if (o instanceof Value) {
            collection.add(o);
        }
    }
    return (List)collection;
}

But so, now my question is how to replace Kotlin’s .filterIsInstance< Value >() with Java, because Java’s Object instanceof Value doesn’t work

if (o instanceof Value) {
    collection.add(o);
}

You miss a step. this.getClass().getFields() gives you the java reflection Field representations. In Kotlin valueField[this] then retrieves the actual value of a field for the given instance. In java you have to use get(<instance>), too:

    for (Field f : this.getClass().getFields())
    {
        f.setAccessible(true);
        Object o = f.get(this);
        if (o instanceof Value) {
            collection.add(o);
        }
    }

Having said that, using reflection to collect values from arbitrary fields of an object is a pretty bad hacky code style…

1 Like

Version 1:

public List<Value> getValues() {
	var list = new ArrayList<Value>();
	for (var field : getClass().getDeclaredFields()) {
		field.setAccessible(true);
		var value = field.get(this);
		if (value instanceof Value) {
			list.add((Value) value);
		}
	}
	return list;
}

Version 2:

public List<Value> getValues() {
	return Arrays.stream(getClass().getDeclaredFields())
		.peek(field -> field.setAccessible(true))
		.map(field -> field.get(this))
		.filter(value -> value instanceof Value)
		.map(value -> (Value) value)
		.collect(Collectors.toList());
}

Just to note we skipped checked exception handling here, so it will need a little extra to actually work.

2 Likes