jeudi 4 octobre 2018

What's the Java equivalent of this C# reflection method

I'm rewriting a framework originally done in C# into Java and this has me stumped. It's a method using reflection to return any property in a class that implements a particular interface using LINQ:

   public List<TInterface> GetElementsOfType<TInterface>()
    {
        return GetType().GetProperties()
            .Where(x => typeof(TInterface).IsAssignableFrom(x.PropertyType))
            .Select(x => x.GetValue(this, null)).OfType<TInterface>()
            .ToList();
    }

I am trying to recreate in Java and so far have this. Not too sure if it's right though?:

    public <T> List<?> GetElementsOfType(Class<T> klazz) {
    Class<?> props = this.getClass();
    List<T> elementsOfType = new ArrayList<>();
    try {
            Field fieldlist[] = props.getDeclaredFields();
            for (Field aFieldlist : fieldlist) {
                if (aFieldlist.getType().isAssignableFrom(klazz)){
                    elementsOfType.add((T)aFieldlist);
                }
            }

        } catch (Exception e) {
            return null;
        }
        return elementsOfType;
}





Aucun commentaire:

Enregistrer un commentaire