Last active
September 12, 2019 12:46
-
-
Save shrys/8dcb6299aecb9c282b1eb57703666582 to your computer and use it in GitHub Desktop.
object initialization by passing CassandraRow using reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.Serializable; | |
import java.lang.reflect.InvocationTargetException; | |
import com.datastax.spark.connector.japi.CassandraRow; | |
import com.datastax.spark.connector.japi.CassandraJavaUtil; | |
import scala.collection.Iterator; | |
class main { | |
public main(CassandraRow row) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, | |
NoSuchMethodException, SecurityException, NoSuchFieldException { | |
Iterator<String> it = row.fieldNames().columnNames().iterator(); | |
while (it.nonEmpty()) { | |
String var = "", columnName = it.next(); | |
String[] column = columnName.split("_"); | |
for (String str : column) { | |
var += str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase(); | |
} | |
Class<?> colType = this.getClass().getDeclaredField(var).getType(); | |
Object value = row.get(columnName, CassandraJavaUtil.typeConverter(colType)); | |
this.getClass().getDeclaredMethod("set" + var, colType).invoke(this, value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment