Skip to content

Instantly share code, notes, and snippets.

@deadblue
Last active November 27, 2019 05:50
Show Gist options
  • Save deadblue/096caf0ec9ee1582cc31f002d12eb43e to your computer and use it in GitHub Desktop.
Save deadblue/096caf0ec9ee1582cc31f002d12eb43e to your computer and use it in GitHub Desktop.
OjbkHttp
fun main() {
data class Foobar(
@OjbkHttp.FormField("foo")
val foo: String,
@OjbkHttp.FormField("bar")
val bar: Int = 0
)
val bean = Foobar("hello,world", 1234)
val form = OjbkHttp.toFormBody(bean)
// TODO: post the form
}
import okhttp3.FormBody
import java.beans.Introspector
import java.lang.reflect.Method
object OjbkHttp {
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class FormField (
val fieldName: String
)
private val metadataCache = HashMap<Class<Any>, HashMap<String, Method>>()
private fun getFormMetadata(clazz: Class<Any>): HashMap<String, Method> {
synchronized(clazz) {
var entry = metadataCache[clazz]
if(entry == null) {
entry = HashMap()
for(pd in Introspector.getBeanInfo(clazz).propertyDescriptors) {
if(pd.readMethod == null) { continue }
try {
val ffa = clazz.getDeclaredField(pd.name).getAnnotation(FormField::class.java)
if(ffa != null) {
entry[ffa.fieldName] = pd.readMethod
}
} catch (ignored: Exception) {}
}
metadataCache[clazz] = entry
}
return entry
}
}
fun toFormBody(value: Any): FormBody {
val fbb = FormBody.Builder()
getFormMetadata(value.javaClass).forEach { (fieldName, reader) ->
val fieldValue = reader.invoke(value)
if(fieldValue != null) {
fbb.add(fieldName, fieldValue.toString())
}
}
return fbb.build()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment