How do I convert a type to a string that can be compiled in vb .net? - vb.net

I need a function that will convert a type to a string, for example:
Dim foo as Dictionary(of Dictionary(of Integer, String), Integer)
Debug.WriteLine(TypeToString(GetType(foo)))
In the debug output, I'd expect to see something equivalent to:
Dictionary(of Dictionary(of Integer, String), Integer)

Here's some extension methods I use to do what you ask, but it's in C# and generate C#.
You can either keep it in C#, but change the output to VB.Net or do a full conversion to VB.Net if you like.
public static string ToCode(this Type #this)
{
string #return = #this.FullName ?? #this.Name;
Type nt = Nullable.GetUnderlyingType(#this);
if (nt != null)
{
return string.Format("{0}?", nt.ToCode());
}
if (#this.IsGenericType & !#this.IsGenericTypeDefinition)
{
Type gtd = #this.GetGenericTypeDefinition();
return string.Format("{0}<{1}>", gtd.ToCode(), #this.GetGenericArguments().ToCode());
}
if (#return.EndsWith("&"))
{
return Type.GetType(#this.AssemblyQualifiedName.Replace("&", "")).ToCode();
}
if (#this.IsGenericTypeDefinition)
{
#return = #return.Substring(0, #return.IndexOf("`"));
}
switch (#return)
{
case "System.Void":
#return = "void";
break;
case "System.Int32":
#return = "int";
break;
case "System.String":
#return = "string";
break;
case "System.Object":
#return = "object";
break;
case "System.Double":
#return = "double";
break;
case "System.Int64":
#return = "long";
break;
case "System.Decimal":
#return = "decimal";
break;
case "System.Boolean":
#return = "bool";
break;
}
return #return;
}
public static string ToCode(this IEnumerable<Type> #this)
{
var #return = "";
var ts = #this.ToArray<Type>();
if (ts.Length > 0)
{
#return = ts[0].ToCode();
if (ts.Length > 1)
{
foreach (Type t in ts.Skip<Type>(1))
{
#return = #return + string.Format(", {0}", t.ToCode());
}
}
}
return #return;
}

Isn't foo.GetType().ToString() acceptable for you? In the example case it will return
System.Collections.Generic.Dictionary`2[System.Collections.Generic.Dictionary`2[System.Int32,System.String],System.Int32]

Related

Pass Type into function in Kotlin

In Swift you can pass a type into a function like so:
func foo<T>(_ type: T.Type)
foo(String.self)
Is there any equivalent in Kotlin?
I don't want to specify the type in the generic arguments, because there are multiple generic arguments and it would be annoying to have to specify them all when the compiler can work it out itself except for this one. Also I don't want to use KClass as that requires the type to by Any which I don't want to make a requirement for the type.
you can you class.java.typeName
/**
* Return an informative string for the name of this type.
*
* #return an informative string for the name of this type
* #since 1.8
*/
public String getTypeName() {
if (isArray()) {
try {
Class<?> cl = this;
int dimensions = 0;
do {
dimensions++;
cl = cl.getComponentType();
} while (cl.isArray());
StringBuilder sb = new StringBuilder();
sb.append(cl.getName());
for (int i = 0; i < dimensions; i++) {
sb.append("[]");
}
return sb.toString();
} catch (Throwable e) { /*FALLTHRU*/ }
}
return getName();
}
foo(Int::class.java.typeName)
foo(String::class.java.typeName)

DI container can't find a class

I have an existing application with line below
\Yii::$container->invoke([$this, 'injections']);
and this line couses the error
ReflectionException Class Redis does not exist
I have a file Redis.php where defined class Redis in the /common/components directory.
But yii looks for it at the /common/components/myAPI/
А class that contains a line
\Yii::$container->invoke([$this, 'injections']);
ia located by the path /common/components/myAPI/
The whole class where I try to call the Redis
abstract class AEntity{
const API_BE_SOCCER_COUNTER = 'API_BE_SOCCER_COUNTER';
/**
* #var Fetcher $_fetcher
* #var boolean $_isFromCache
* #var APIConfig $_config
* #var string $_redisKey
* #var array $_params
*/
private $_fetcher,
$_isFromCache = null,
$_params = [],
$_redisKey = null,
$_mainApi;
/**
* #var APIRedisManager $_redis
*/
private $_redis,
$_config;
/**
* #var Array $_dbTable
* #var Array $_dbMap
*/
protected $_dbMap,
$_dbTable;
/**
*
* #return array
*/
protected function setParams(Array $params = []){
$this->_params = $params;
}
protected abstract function keyRelationShip();
protected abstract function getAttributes();
protected abstract function jsonArrayMap();
protected function setRedisKey($redisData){
$this->_redisKey = $redisData;
}
protected function mapArrays(){
$jsonArrayMap = $this->jsonArrayMap();
foreach ($jsonArrayMap as $arrayMap){
$mapPath = $arrayMap['path'] ? explode('.', $arrayMap['path']) : null;
$key = $arrayMap['key'];
$arr = $arrayMap['array'];
$assoc = $arrayMap['assoc'];
$tmpData = $this->_mainApi;
if($mapPath){
foreach($mapPath as $mapper) {
if(!isset($tmpData[$mapper])){
$this->{$key} = null;
return false;
}
$tmpData = $tmpData[$mapper];
}
}
$this->{$key} = $arr ? $this->jsonArrayMapper($tmpData, $assoc, $mapPath) : $tmpData;
}
}
public function injections(APIConfig $config, Fetcher $fetcher, APIRedisManager $redisManager){
$this->_config = $config;
$this->_fetcher = $fetcher;
$this->_redis = $redisManager;
}
protected function initialize(Array $params = []){
$constant = static::keyRelationShip();
$redisKey = $this->paramToRedis($params);
$this->setParams($params);
$this->setRedisKey($redisKey);
\Yii::$container->invoke([$this, 'injections']);
$this->_config->get($constant, $this->_params);
$this->_redis->setConfig($this->_config);
$this->_fetcher->setConfig($this->_config);
$this->_mainApi = $this->getAPIRequest();
$this->mapArrays();
}
/**
* #return array
*/
public function getMainApi(){
return $this->_mainApi;
}
/**
* #return APIRedisManager
*/
public function getRedis(){
return $this->_redis;
}
/**
* #return array
* #throws \Exception
*/
public function loadYiiData(){
$arrModel = [];
if (!$this->_dbTable) new Exception('No Table Specified.');
if (!$this->_dbMap) new Exception('No DB Map Specified.');
foreach ($this->_dbMap as $keyApi => $keyDB){
if(!isset($this->$keyDB)) throw new \Exception("KeyDB: $keyDB, is not Set");
$arrModel[$this->_dbTable][$keyApi] = $this->$keyDB;
}
return $arrModel;
}
/**
* GET API request logic
*
* #return array
*/
public function getAPIRequest(){
$redisKey = $this->formulateRedisKeyLogic();
$storedRequest = $this->_redis->getConfig() ? $this->_redis->get($redisKey) : null;
if(!$storedRequest){
$this->_isFromCache = false;
$apiRequestResult = $this->_fetcher->get()->asArray();
$this->_redis->incrCounter();
if($apiRequestResult && !$storedRequest){
$serializedApiRequest = serialize($apiRequestResult);
$this->_redis->store($serializedApiRequest, $redisKey);
}
}else{
$this->_isFromCache = true;
$apiRequestResult = unserialize($storedRequest);
}
return $apiRequestResult;
}
/** #return boolean */
public function isFromCache(){
return $this->_isFromCache;
}
private function formulateRedisKeyLogic(){
$config = $this->_redis->getConfig();
if(isset($config['key']) && strpos($this->_redisKey,'$.')!==false){
$configKey = $config['key'];
$redisKey = $configKey . $this->_redisKey;
$redisKey = str_replace('$.', '', $redisKey);
}
else{
$redisKey = $this->_redisKey;
}
return $redisKey;
}
protected function paramToRedis($param){
$className = (new \ReflectionClass($this))->getShortName();
$buildRedisKey = '$._'.str_replace('=', '_', http_build_query($param, null, ','));
$paramKey = $buildRedisKey.'_'.$className;
return $paramKey;
}
/**
* GET API request logic
*
* #return array
*/
protected function jsonArrayMapper(Array $entityItems, $assoc = false, $mapPath= true){
$aEntityArray = [];
$attributes = $this->getAttributes();
$Klass = static::class;
if($mapPath){
foreach ($entityItems as $entityItem){
$aEntity = new $Klass(false);
foreach ($attributes as $attribute){
$aEntity->{$attribute} = $entityItem[$attribute];
}
$assoc ? $aEntityArray[$entityItem[$assoc]] = $aEntity : $aEntityArray[] = $aEntity;
}
}else{
$aEntity = new $Klass(false);
foreach ($attributes as $attribute){
$aEntity->{$attribute} = $entityItems[$attribute];
}
$aEntityArray = $aEntity;
}
return $aEntityArray;
}
public function __set($key, $value){
$this->{$key} = $value;
}
public function __get($name) {
return $this->{$key};
}
}
This is a super class for class those have such constructor
public function __construct($fullInitizalization=true, $params = []) {
if($fullInitizalization){
$redisParams = $this->paramToRedis($params);
parent::initialize($params);
}
}
When DI container trying to instaniate APIRedisConnection class, it passes parameter with type Redis:
/** #param Redis $redis */
function __construct(Redis $redis){
$this->_redis = $redis;
}
Class Redis can't be found in the project, but I can see it in IDE and this class was written on PHP 7
Although the whole project written on PHP 5.6

get and set methods from an ArrayList in another class

/*
* Notes here
*/
package billboardsign;
/**
*
* #author John Parada
*/
import java.util.ArrayList;
public class Billboard
{
private String text;
private ArrayList<String> messages = new ArrayList<String>();
public Billboard()
{
messages.add("Happy New Year");
messages.add("Happy Holidays");
messages.add("Team Pizza");
messages.add("Game On");
messages.add("Let's Go Team");
}
public ArrayList<String> getMessages()
{
return messages;
}
public void setMessages(String msg)
{
messages.add(msg);
}
public boolean isEmpty()
{
return text == null || text.isEmpty();
}
public String substring(int begin, int end)
{
if (begin >= 0 && end < text.length())
{
return text.substring(begin, end);
}
else
return null;
}
//add the method Reverse here
// THIS CODE IS NO GOOD!for (int count = text.length() - 1; count >= 0; count-- )
//FOLLOW UP LINE System.out.printf( "%s ", text.charAt( count ) );
public String reverse()
{
if (isEmpty())
return null;
else
{
char[] chars = text.toCharArray();
//create antoher arrayList
char[] reverse = new char[chars.length];
for (int i = chars.length - 1, j = 0; i < 0; i--, j++)
{
reverse[j] = chars[i];
}
return new String(reverse);
}
}
//add the method Replace string here
public String replace(char oldChar, char newChar)
{
return text.replace(oldChar, newChar);
}
//add the method displayInfo here
public void displayInfo()
{
System.out.printf("\n%s\nMessage", messages);
}
}
/*
* Notes on the Billboard Project
*/
package billboardsign;
/**
*
* #author John Parada
*/
import java.util.Scanner;
public class BillboardSign
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Billboard newBillboard = new Billboard(); //default constructor
//Menu
int choose_again = 1;
int choiceNumber;
Scanner newInput = new Scanner(System.in);
while (choose_again > 0 )
{
//list options to user
System.out.println ("\nPlease choose a number between 1 and 6 to choose an\n"
+ "option for the Messages Board to display: "
+ "\n1) Display Default Message 1"
+ "\n2) Display Default Message 2"
+ "\n3) Display Default Message 3"
+ "\n4) Display Default Message 4"
+ "\n5) Display Default Message 5"
+ "\n6) Enter a New Message"
+ "\n7) Reverse a Message"
+ "\n8) Replace a Message - Substring"
+ "\n9) Exit Program");
//get the user to input a selection
System.out.print ("\nPlease Enter Your Selection: ");
choiceNumber = newInput.nextInt();
//use switch statement to help with thieir choice input
switch (choiceNumber)
{
case 1:
//execute get() and displayInfo() method for default Message 1
//newBillboard = Billboard();
messages.get(0);
displayInfo();
break;
case 2:
//execute get() and displayInfo() method for default Message 2
newBillboard = Billboard();
Billboard = displayInfo();
break;
case 3:
//execute get() and displayInfo() method for default Message 3
newBillboard = Billboard();
Billboard = displayInfo();
break;
case 4:
//execute get() and displayInfo() method for default Message 4
newBillboard = Billboard();
Billboard = displayInfo();
break;
case 5:
displayInfo();
break;
case 6:
//execute set() and displayInfo() methods to create a new message
break;
case 7:
//execute reverse message method
break;
case 8:
//execute Replace message - Substring method
case 9:
//Dispaly to the user that they have chose to exit
System.out.print ("\nYou have chosen to cancel and exit. \n");
System.exit(0);
}
//prompt user for antother selection? (Contiune=1 and Exit= -1)
System.out.println();
System.out.print ("\nIf you would like to select another animal enter 1 or if your are done enter -1: ");
choose_again = newInput.nextInt();
}
}
private static void displayInfo() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
In short, when the user selects 1, he or she is supposed to get the first element of the ArrayList(0). When he or she selects 2, they will get the second element in the ArrayList(1). I need to invoke the get method, and use the displayInfo of the Billboard.
Thank you in advance for any and all help.
Regards,
John Parada
do something likewise,
case 1:
newBillboard.getMessages().get(0);
...
case 1:
newBillboard.getMessages().get(1);
....
And so on.
your getMessages() method is returning an arraylist so either you should have in an arraylist variable in your main class like this
ArrayList<String> messages = newBillboard.getMessages();
and then call it like this
case 1:
//execute get() and displayInfo() method for default Message 1
//newBillboard = Billboard();
System.out.println (messages.get(0));
//displayInfo();
break;
or you can simply call it like this
newBillboard.getMessages.get(0);//here 0 is for first element
and there is no need to get an object of your class in every case
and what is the need of displayInfo is unclear so if you tell why have you added that i might see to it.

How to deserialize a JSON array to a singly linked list by using Jackson

I want to deserialize a JSON array to a singly linked list in Java.
The definition of singly linked list is as the following:
public class SinglyLinkedListNode<T> {
public T value;
public SinglyLinkedListNode next;
public SinglyLinkedListNode(final T value) {
this.value = value;
}
}
How to deserialize a JSON string such as [1,2,3,4,5] in to a singly linked list?
public void typeReferenceTest() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
final ArrayList<Integer> intArray = objectMapper.readValue("[1,2,3,4,5]",
new TypeReference<ArrayList<Integer>>() {});
System.out.println(intArray);
// How to achieve this?
final ArrayList<Integer> intList = objectMapper.readValue("[1,2,3,4,5]",
new TypeReference<SinglyLinkedListNode<Integer>>() {});
System.out.println(intList);
}
Moreover, I want the SinglyLinkedListNode to be a first-class citizen the same as ArrayList, which can be used in all kinds of combinations, such as HashSet<SinglyLinkedListNode<Integer>>, SinglyLinkedListNode<HashMap<String, Integer>>.
For example, what happens if I want to deserialize [[1,2,3], [4,5,6]] into a ArrayList<SinglyLinkedListNode<Integer>> ?
As far as I know, a customized deserializer extending JsonDeserializer is not enough to do this.
When you want it to be deserialized to ArrayList<SinglyLinkedListNode<Integer>> for example. Your code specifies that is the type that expected. Therefore it should if a deserializer for SinglyLinkedListNode<Integer> is regeistered it will succeed.
From the jackson-user google group I get the right answer from #Tatu Saloranta.
The answer is simple: just implement the java.util.List interface, and Jackson will automatically serialize/deserialize between JSON array and SinglyLinkedListNode.
So I implement the java.util.List interface for SinglyLinkedListNode, the code is as the following:
import java.util.*;
import java.util.function.Consumer;
/**
* Singly Linked List.
*
* <p>As to singly linked list, a node can be viewed as a single node,
* and it can be viewed as a list too.</p>
*
* #param <E> the type of elements held in this collection
* #see java.util.LinkedList
*/
public class SinglyLinkedListNode<E>
extends AbstractSequentialList<E>
implements Cloneable, java.io.Serializable {
public E value;
public SinglyLinkedListNode<E> next;
/**
* Constructs an empty list.
*/
public SinglyLinkedListNode() {
value = null;
next = null;
}
/**
* Constructs an list with one elment.
*/
public SinglyLinkedListNode(final E value) {
this.value = value;
next = null;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* #param c the collection whose elements are to be placed into this list
* #throws NullPointerException if the specified collection is null
*/
public SinglyLinkedListNode(Collection<? extends E> c) {
this();
addAll(c);
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final SinglyLinkedListNode<E> l = last();
final SinglyLinkedListNode<E> newNode = new SinglyLinkedListNode<>(e);
if (l == null)
this.value = e;
else
l.next = newNode;
modCount++;
}
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, SinglyLinkedListNode<E> succ) {
assert succ != null;
final SinglyLinkedListNode<E> prev = this.previous(succ);
final SinglyLinkedListNode<E> newNode = new SinglyLinkedListNode<>(e);
if (prev == null)
this.value = e;
else
prev.next = newNode;
modCount++;
}
/**
* Return the node before x.
*
* #param x current node
* #return the node before x
*/
private SinglyLinkedListNode<E> previous(final SinglyLinkedListNode<E> x) {
assert (x != null);
if (size() < 2) return null;
if (this == x) return null;
SinglyLinkedListNode<E> prev = new SinglyLinkedListNode<>();
prev.next = this;
SinglyLinkedListNode<E> cur = this;
while (cur != x) {
prev = prev.next;
cur = cur.next;
}
return prev;
}
/**
* Return the last node.
* #return the last node.
*/
private SinglyLinkedListNode<E> last() {
if (size() == 0) return null;
if (size() == 1) return this;
SinglyLinkedListNode<E> prev = new SinglyLinkedListNode<>();
prev.next = this;
SinglyLinkedListNode<E> cur = this;
while (cur != null) {
prev = prev.next;
cur = cur.next;
}
return prev;
}
/**
* Unlinks non-null node x.
*/
E unlink(SinglyLinkedListNode<E> x) {
assert x != null;
final E element = x.value;
final SinglyLinkedListNode<E> next = x.next;
final SinglyLinkedListNode<E> prev = previous(x);
if (prev == null) {
this.value = next.value;
this.next = next.next;
} else {
prev.next = next;
}
x.next = null;
modCount++;
return element;
}
/**
* #inheritDoc
*/
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator<E> {
private SinglyLinkedListNode<E> lastReturned;
private SinglyLinkedListNode<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
assert isPositionIndex(index);
next = (index == size()) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size();
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.value;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
throw new UnsupportedOperationException();
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
unlink(lastReturned);
nextIndex--;
lastReturned = null;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.value = e;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size()) {
action.accept(next.value);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
/**
* #inheritDoc
*/
public int size() {
int size = 0;
if (value == null) return size;
SinglyLinkedListNode<E> cur = this;
while (cur != null) {
size++;
cur = cur.next;
}
return size;
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Returns the (non-null) Node at the specified element index.
*/
SinglyLinkedListNode<E> node(int index) {
assert isElementIndex(index);
SinglyLinkedListNode<E> x = this;
for (int i = 0; i < index; i++)
x = x.next;
return x;
}
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size();
}
/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size();
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: " + size();
}
}
Here is the unit test code:
#Test public void typeReferenceTest() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
final SinglyLinkedListNode<Integer> intList = objectMapper.readValue("[1,2,3,4,5]",
new TypeReference<SinglyLinkedListNode<Integer>>() {});
System.out.println(intList);
final ArrayList<SinglyLinkedListNode<Integer>> arrayOfList = objectMapper.readValue("[[1,2,3], [4,5,6]]",
new TypeReference<ArrayList<SinglyLinkedListNode<Integer>>>() {});
System.out.println(arrayOfList);
}
#Tatu Saloranta Thank you very much!
Here is my original blog, Deserialize a JSON Array to a Singly Linked List

Extracting ResultSetMetaData from Spring JdbcTemplate

I am trying to fetch the resultsetmeta data using Spring jdbc template. It works fine if there is atleast one row returned.
The problem arises when there is no rows returned i.e. an empty resultSet.
I have tried a lot and still stuck up with the same. If there is any solution to this, please help me with this.
Also, I found ResultSetWrappingSqlRowSetMetaData class in spring. Is this of some use in my context?
Thanks for the help.
Finally I found the answer to my question. Below is the code:
template.query(builder.toString(),new ResultSetExtractor<Integer>() {
#Override
public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for(int i = 1 ; i <= columnCount ; i++){
SQLColumn column = new SQLColumn();
column.setName(rsmd.getColumnName(i));
column.setAutoIncrement(rsmd.isAutoIncrement(i));
column.setType(rsmd.getColumnTypeName(i));
column.setTypeCode(rsmd.getColumnType(i));
column.setTableName(sqlTable.getName().toUpperCase());
columns.add(column);
}
return columnCount;
}
});
For a detailed explanation you can visit here
You can also use JdbcUtils
#SuppressWarnings("unchecked")
public static List<TableColumnTypeMap> getTableColumns(DataSource dataSource,
String tableName) {
try {
return (List<TableColumnTypeMap>) JdbcUtils.extractDatabaseMetaData(dataSource,
new DatabaseMetaDataCallback() {
#Override
public Object processMetaData(DatabaseMetaData dbmd)
throws SQLException, MetaDataAccessException {
ResultSet rs = dbmd
.getColumns("", "%", tableName + "%", null);
List<TableColumnTypeMap> list = new ArrayList();
while (rs.next()) {
String tableCat = rs.getString("TABLE_CAT");
String tableSchem = rs.getString("TABLE_SCHEM");
String tableName = rs.getString("TABLE_NAME");
String columnName = rs.getString("COLUMN_NAME");
String typeName = rs.getString("TYPE_NAME");
String columnSize = rs.getString("COLUMN_SIZE");
String nullable = rs.getString("NULLABLE");
String remarks = rs.getString("REMARKS");
int dataType = rs.getInt("DATA_TYPE");
System.out.println(tableName);
TableColumnTypeMap tableColumnTypeMap = new TableColumnTypeMap()
.setColumnName(columnName)
.setColumnType(typeName)
.setJavaClassName(getColumnCLassName(dataType))
.setRemarks(remarks);
list.add(tableColumnTypeMap);
}
return list;
}
});
} catch (MetaDataAccessException ex) {
throw new RuntimeException("get table list failed", ex);
}
}
for java class map:
private static String getColumnCLassName(int sqlType) {
String className = String.class.getName();
switch (sqlType) {
case Types.NUMERIC:
case Types.DECIMAL:
className = java.math.BigDecimal.class.getName();
break;
case Types.BIT:
className = java.lang.Boolean.class.getName();
break;
case Types.TINYINT:
className = java.lang.Byte.class.getName();
break;
case Types.SMALLINT:
className = java.lang.Short.class.getName();
break;
case Types.INTEGER:
className = java.lang.Integer.class.getName();
break;
case Types.BIGINT:
className = java.lang.Long.class.getName();
break;
case Types.REAL:
className = java.lang.Float.class.getName();
break;
case Types.FLOAT:
case Types.DOUBLE:
className = java.lang.Double.class.getName();
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
className = "byte[]";
break;
case Types.DATE:
className = java.sql.Date.class.getName();
break;
case Types.TIME:
className = java.sql.Time.class.getName();
break;
case Types.TIMESTAMP:
className = java.sql.Timestamp.class.getName();
break;
case Types.BLOB:
className = java.sql.Blob.class.getName();
break;
case Types.CLOB:
className = java.sql.Clob.class.getName();
break;
default:
break;
}
return className;
}
for result class
/**
* #author ryan
* #date 19-7-15 下午6:05
*/
#Data
#Accessors(chain = true)
public class TableColumnTypeMap {
private String columnName;
private String columnType;
private String javaClassName;
private String remarks;
}