0

I want to find memberProperties that are not other classes I declared.

For example

data class X(val other: String)
data class Y(val str: String, val y: X?)

I want to filter() my Y::class.memberProperties such that only str is included.

In other words, I want to only return built-in types, such as java.util.Date, String, Int, Long, BigDecimal, Decimal, Double...etc and their nullable counterparts.

What I tried (and that doesn't work):

Y::class.memberProperties.filter { it.returnType.javaClass.isPrimitive } (returned 0 properties)

Update:

I managed to work around my issue for now like so:

Y::class.memberProperties.filter { !it.returnType.javaType.typeName.startsWith("com.myapp") }

However, this is plenty fragile as if I use any third party libs I might end up with types also included.

To make it clearer and give a more practical example, I am looking to exclude ALL types which, when serialized to JSON, do NOT serialize with properties beginning with {.

zaitsman
  • 8,984
  • 6
  • 47
  • 79
  • You question is not clear. You want to get your defined datatype or you want to check the data type is primitive or not ? – Zeeshan Ali Mar 08 '22 at 05:36
  • 1
    @ZeeshanAli as it clearly states in the question `I want to filter() my Y::class.memberProperties such that only str is included.` I don't want to check the data type nor do i want to check my defined type. I want to get memberProperties which are NOT my types, e.g. `Int?, Int, Long, Long?, java.util.Date, String, String?` etc – zaitsman Mar 08 '22 at 05:51

1 Answers1

-1

First of, in Java, Strings are not a primitive type. Secondly, it seems the way to check it is to do it.returnType.jvmErasure.java.isPrimitive

For example

fun main() {
    Y::class.memberProperties.forEach {
        println("${it.name} is primitive: ${it.returnType.jvmErasure.java.isPrimitive}")
    }
}

data class X(val other: String)
data class Y(val int: Int, val str: String, val y: X?)

this will print

int is primitive: true
str is primitive: false
y is primitive: false
Ivo
  • 18,659
  • 2
  • 23
  • 35
  • Ok i want all properties that are not a class, how do I do that? – zaitsman Mar 08 '22 at 09:01
  • @zaitsman I don't think there is a clear definition of what you consider to be a class. Because `String` is in fact a class – Ivo Mar 08 '22 at 09:04
  • see also https://stackoverflow.com/questions/12717451/why-is-string-a-class – Ivo Mar 08 '22 at 09:07