🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Reflection in Depth

Reflection in depth is inspecting a type and a value to learn its fields and its identity. It lists fields, checks for a field, and names the type and its module.

Reflection lists fields and their types

The struct has two integer fields, and reflection lists both in order.

struct Point
    x::Int
    y::Int
end
println(fieldnames(Point))
println(fieldtypes(Point))

Reflection checks a value and a field name

The value has fields x and y, the type has x, and the type does not have z.

struct Point
    x::Int
    y::Int
end
p = Point(3, 4)
println(propertynames(p))
println(hasfield(Point, :x))
println(hasfield(Point, :z))

Reflection names a type and its module

The type name is Point, and its module is Main.

struct Point
    x::Int
    y::Int
end
println(nameof(Point))
println(parentmodule(Point))

Example

struct Point
    x::Int
    y::Int
end
p = Point(3, 4)
println(fieldnames(Point))
println(propertynames(p))
println(hasfield(Point, :y))
println(nameof(Point))
println(parentmodule(Point))

Key points

  • Field list: fieldnames gives the fields of a struct type as symbols in order.
  • Field types: fieldtypes gives the type of each field in the same order.
  • Value fields: propertynames gives the fields of a value.
  • Field check: hasfield tells whether a type has a named field.
  • Type name: nameof gives the name of a type as a symbol.
  • Module: parentmodule gives the module where a type was defined.

In this example, fieldnames lists x and y, propertynames lists the same fields for the value, hasfield confirms y, and the name and module follow.

Note

Field order is the order the fields were written in the struct definition.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does fieldnames return?