简体   繁体   English

通过对象类型Java引用

[英]Referencing by an object type Java

Is it possible to reference an object by it's type in Java? 是否可以通过Java中的类型引用对象?

For example, I have this: 例如,我有这个:

private static class Pet {
    private String name;

    public String getName() {
        return name;
    }

    public Pet setName(String name) {
        this.name = name;
        return this;
    }
}

public static class CAT extends Pet{}

public static class DOG extends Pet{}

I put a bunch of pets of CATS and DOGS into a linked list that accepts Pets. 我把一堆CATS和DOGS宠物放入一个接受宠物的链接列表中。 I want to find the last index a DOG via: 我想通过以下方式找到DOG的最后一个索引:

        private Pet dequeueDog() {
        int locationDog = linkedList.lastIndexOf(DOG);
        return linkedList.remove(locationDog);
    }

Is it possible to do so? 有可能这样做吗? To reference an object by the type of object it is? 通过对象类型引用对象是什么?

Assuming you're using Java 8, you can filter out all non- DOG s to find the last dog then search for that: 假设您正在使用Java 8,您可以filter掉所有非DOG以找到最后一只狗然后搜索它:

private static Pet dequeueDog(LinkedList<Pet> linkedList) {

    List<Pet> dogList = linkedList.stream().filter(u -> u.getClass() == DOG.class).collect(Collectors.toList());
    int locationDog = linkedList.lastIndexOf(dogList.get(dogList.size()-1));
    return linkedList.remove(locationDog);
}

Here 's an example where I put in two DOG s and three CAT s to the list, and receive the second DOG I put into the set. 是一个例子,我将两个DOG和三个CAT放入列表中,并接收我放入集合中的第二个DOG You could extend this to remove the n th DOG by changing what you put into dogList.get() . 您可以通过更改放入dogList.get()来扩展此以删除第nDOG

It is possible in Java, but a bit ugly. 它有可能在Java中,但有点难看。 Here is a method that will do it, given a list and a type that you want to search for. 给定一个要搜索的列表和类型,这是一个可以执行此操作的方法。

public static <T> T getLastOfType(List<? super T> list, Class<T> type) {
    Object[] arr = list.toArray();
    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] == null) continue;

        if (type.isAssignableFrom(arr[i].getClass())) {
            return (T) arr[i];
        }
    }
    return null;
}

And here is a little test of it in action: http://pastebin.com/yX1v6L9p (Note that the explicit type parameters aren't strictly needed.) 以下是对它的实际应用的一点测试: http//pastebin.com/yX1v6L9p (注意,不严格需要显式类型参数。)

This works by utilizing generics and the Class method isAssignableFrom to check the types of the objects in the list against the desired type. 这通过使用泛型和Class方法isAssignableFrom来检查列表中对象的类型与所需类型。

Use instanceof like so. 像这样使用instanceof

package com.example;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class ExampleTest {

    class Pet {
    }

    class CAT extends Pet {
    }

    class DOG extends Pet {
    }

    private Pet dequeueDog(List<Pet> linkedList) {
        int i = 0;
        Integer foundIndex = null;
        DOG found = null;
        for (Pet pet : linkedList) {
            if (pet instanceof DOG) {
                foundIndex = i;
                found = (DOG) pet;
            }
        }
        if (foundIndex != null) {
            linkedList.remove(foundIndex);
        }
        return found;
    }

    @Test
    public void test() {
        DOG someDog = new DOG();
        CAT someCat = new CAT();
        assertEquals(someDog, dequeueDog(Arrays.asList(someCat, someDog, null, someDog, someCat)));
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM