Ghi đè phương thức hỗ trợ Java (ràng buộc kiểu động), nhưng không phải những gì bạn đang cố gắng đạt được (quá tải là tính đa hình tĩnh và không động).
Để đạt được những gì bạn muốn đạt được trong Java, bạn cần công văn kép.
Mẫu khách truy cập phải là bạn của bạn ở đây.
Tôi đã viết cho bạn một mẫu mã.
public class Test {
public static void main(String argsp[]) {
PrintTypeImpl typeImpl = new PrintTypeImpl(new StringType(), new IntType(), new ObjectType());
typeImpl.accept(new PrintVisitor());
}
static final class PrintVisitor implements TypeVisitor {
public void visit(IntType x) {
System.out.println("Int: ");
}
public void visit(StringType x) {
System.out.println("String: ");
}
public void visit(ObjectType x) {
System.out.println("Object: ");
}
}
interface TypeVisitor {
void visit(IntType i);
void visit(StringType str);
void visit(ObjectType obj);
}
interface PrintType {
void accept(TypeVisitor visitor);
}
static class StringType implements PrintType {
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
static class ObjectType implements PrintType {
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
static class IntType implements PrintType {
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
static final class PrintTypeImpl implements PrintType {
PrintType[] type;
private PrintTypeImpl(PrintType... types) {
type = types;
}
@Override
public void accept(TypeVisitor visitor) {
for (int i = 0; i < type.length; i++) {
type[i].accept(visitor);
}
}
}
}
xem câu hỏi này vào việc loại T - [Get Generic Loại Lớp tại Runtime] (http: // stackoverflow .com/questions/3403909/get-generic-type-of-class-at-runtime) – csturtz