You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@avro.apache.org by Andy Le <an...@gmail.com> on 2020/03/22 03:04:21 UTC

Java Reflection: Array of Union

Hi guys,

Avro spec allows us to have an array of unions. Would you please tell me how to construct such schemas using reflection?

1. For classes

It's easy

```java
public class Human extends Kind {
  String name = "Andy";
  ArrayList<Human> friends = new ArrayList<>();
}

public class Machine extends Kind {
  String name = "BB-8";
}

@Union({ Human.class, Machine.class })
public  class Kind extends Object {
  
}
public class Meta {
  @Nullable
  List<Kind> kinds;
}
public void testDefaults() {
  Schema schema = ReflectData
        .get()
        .getSchema(Meta.class);
  System.out.println(schema.toString(true));
}
```

2. For enums

I'm stuck because enums can be derived.

I think we should have an annotation named as @Items. For example:

```java
enum First{}

enum Second{}

public class Meta {
  @Items(Human.class, Machine.class)
  List<Object> kinds;

  @Items(First.class, Second.class)
  List<Object> ranks;
}
``

Please let me know what you think about this suggestion.

Thank you in advance.


Re: Java Reflection: Array of Union

Posted by Andy Le <an...@gmail.com>.
Never mind. I fixed it 

```java
  @Union({First.class,Second.class})
  public static class Rank {

  }

  public static class Meta {
    List<Rank> ranks ;
  }
```

On 2020/03/22 03:04:21, Andy Le <an...@gmail.com> wrote: 
> Hi guys,
> 
> Avro spec allows us to have an array of unions. Would you please tell me how to construct such schemas using reflection?
> 
> 1. For classes
> 
> It's easy
> 
> ```java
> public class Human extends Kind {
>   String name = "Andy";
>   ArrayList<Human> friends = new ArrayList<>();
> }
> 
> public class Machine extends Kind {
>   String name = "BB-8";
> }
> 
> @Union({ Human.class, Machine.class })
> public  class Kind extends Object {
>   
> }
> public class Meta {
>   @Nullable
>   List<Kind> kinds;
> }
> public void testDefaults() {
>   Schema schema = ReflectData
>         .get()
>         .getSchema(Meta.class);
>   System.out.println(schema.toString(true));
> }
> ```
> 
> 2. For enums
> 
> I'm stuck because enums can be derived.
> 
> I think we should have an annotation named as @Items. For example:
> 
> ```java
> enum First{}
> 
> enum Second{}
> 
> public class Meta {
>   @Items(Human.class, Machine.class)
>   List<Object> kinds;
> 
>   @Items(First.class, Second.class)
>   List<Object> ranks;
> }
> ``
> 
> Please let me know what you think about this suggestion.
> 
> Thank you in advance.
> 
>