Skip to content

Instantly share code, notes, and snippets.

@xujiaji
Created May 10, 2018 01:28
Show Gist options
  • Select an option

  • Save xujiaji/f8dbb667e675353e4927a2e608e89ac1 to your computer and use it in GitHub Desktop.

Select an option

Save xujiaji/f8dbb667e675353e4927a2e608e89ac1 to your computer and use it in GitHub Desktop.
Java中通过反射应用潜在类型机制
public class Apply
{
public static <T, S extends Iterable<? extends T>>
void apply(S seq, Method f, Object ... args)
{
try
{
for(T t : seq)
{
f.invoke(t, args);
}
} catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
@xujiaji
Copy link
Author

xujiaji commented May 10, 2018

使用

class Shape
{
    public void rotate()
    {
        print(this + "rotate");
    }

    public void resize(int newSize)
    {
        print(this + " resize " + newSize);
    }
}

class Square extends Shape
{
}

class FilledList<T> extends ArrayList<T>
{
    public FilledList(Class<? extends T> type, int size)
    {
        try
        {
            for (int i = 0; i < size; i++)
            {
                add(type.newInstance());
            }
        } catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }
}

class ApplyTest
{
    public static void main(String[] args) throws Exception
    {
        List<Shape> shapes = new ArrayList<>();
        for (int i = 0; i < 10; i++)
        {
            shapes.add(new Shape());
        }
        Apply.apply(shapes, Shape.class.getMethod("rotate"));
        Apply.apply(shapes, Shape.class.getMethod("resize", int.class), 5);

        Apply.apply(new FilledList<>(Square.class, 10), Square.class.getMethod("rotate"));
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment